有个map,key值是code,value是金额,想通过下级code获得上级code的金额。例如下图:
00的value的和等于0001+0002的和,依次类推。
代码:
package com.iss.itms.budgetmanage.budgeting.budgetimport; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeMap; import java.util.Map.Entry; public class newSum { public static void main(String[] args) { Map map =new HashMap(); Map sumByCode = sumByCode(map); System.out.println("---节点求和后的数据"+sumByCode.toString()); } /** * 获得对应项目编号的金额数据 * @param column6 * @param column8 * @return */ private static Map sumByCode(Map sumByProjectCode){ sumByProjectCode.put("00", null); sumByProjectCode.put("0001", 3); sumByProjectCode.put("0002", 3); sumByProjectCode.put("01", null); sumByProjectCode.put("0101", 4); sumByProjectCode.put("0102", 5); sumByProjectCode.put("0102", null); sumByProjectCode.put("010201", 2); sumByProjectCode.put("010202", 3); //对map进行降序排序 Map<String, String> sortMap = sortMapByKey(sumByProjectCode); //一下是为了key值在循环的时候能进行remove操作进行的赋值操作 Set<String> keySet = sortMap.keySet(); Set<String> keySet2 = new HashSet<String>(); keySet2.addAll(keySet); List<String> list = new ArrayList<String>(keySet2); Collections.sort(list); //迭代可以值获得和值 for(Entry<String, String> entry : sortMap.entrySet()){ String key = entry.getKey(); Set set=new HashSet(); int sum=0; Object[] array = list.toArray(); for(int i=array.length-1;i>0;i--){ String key2=array[i].toString(); String regex=key+"\d+"; if (key2.matches(regex)) { set.add(key2); //有下级项目类型,就去下级项目金额和,不加本机的金额 sum+=Integer.parseInt(sortMap.get(key2)); }else if(key2.length()<=key.length()){ continue; }else { break; } } if (set.size()!=0) { list.removeAll(set); } //没有下级值才取自己的值信息 if (sum==0) { sum=Integer.parseInt(String.valueOf(sortMap.get(key))); } sortMap.put(key, String.valueOf(sum)); } return sortMap; } /** * 使用 Map按key进行排序 * @param map * @return */ public static Map<String, String> sortMapByKey(Map<String, String> map) { if (map == null || map.isEmpty()) { return null; } Map<String, String> sortMap = new TreeMap<String, String>( new MapKeyComparator()); sortMap.putAll(map); return sortMap; } } class MapKeyComparator implements Comparator<String>{ public int compare(String str1, String str2) { return str2.compareTo(str1);//调换可实现正序倒序 } }
输出为:
---节点求和后的数据{010202=3, 010201=2, 0102=5, 0101=4, 01=9, 0002=3, 0001=3, 00=6}