1.我需要统计支出明细、对于支出明细有两张表 一张是交易表 一张是房租支出表
2.根据需求我可以从两张表中分别查到符合要求的数据并拿到两个list
3.将两个list分别转换为map key是日期 格式为yyyyMMdd value是Bigdecimal类型的金额
4.需要将两个map相合并,日期相同的金额相加
- public static void main(String[] args) {
- Map
map1 = new HashMap<>(); - map1.put("20230101", 100);
- map1.put("20230201", 200);
- map1.put("20230301", 300);
-
- Map
map2 = new HashMap<>(); - map2.put("20230201", 150);
- map2.put("20230301", 250);
- map2.put("20230401", 350);
-
- Map
mergedMap = mergeMaps(map1, map2); - for (Map.Entry
entry : mergedMap.entrySet()) { - System.out.println(entry.getKey() + ": " + entry.getValue());
- }
- }
-
- public static Map
mergeMaps(Map map1, Map map2) { - Map
mergedMap = new HashMap<>(); - for (Map.Entry
entry : map1.entrySet()) { - mergedMap.put(entry.getKey(), entry.getValue());
- }
- for (Map.Entry
entry : map2.entrySet()) { - if (mergedMap.containsKey(entry.getKey())) {
- mergedMap.put(entry.getKey(), mergedMap.get(entry.getKey()) .add( entry.getValue()));
- } else {
- mergedMap.put(entry.getKey(), entry.getValue());
- }
- }
- return mergedMap;
- }
- Map
collect4 = Stream.concat(collect1.entrySet().stream(), collect3.entrySet().stream()) - .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (v1, v2) -> v1.add(v2)));