Map<String, Map<String, Long>> map = new HashMap<>(); Map<String, Long> param1 = new HashMap<>(); param1.put("a", 100L); param1.put("b", 200L); param1.put("c", 500L); map.put("A", param1); Map<String, Long> param2 = new HashMap<>(); param2.put("a", 100L); param2.put("b", 200L); param2.put("c", 800L); param2.put("d", 1000L); map.put("B", param2); System.out.println("map = " + map); Map<String, Long> collect = map.values() .stream() .map(Map::entrySet) .flatMap(Set::stream) .collect( Collectors.groupingBy( Map.Entry::getKey, Collectors.summingLong(Map.Entry::getValue) ) ); System.out.println("collect = " + collect); List<Map.Entry<String, Long>> collect1 = map.values() .stream() .map(Map::entrySet) .flatMap(Set::stream) //.distinct() .collect(Collectors.toList()); System.out.println("collect1 = " + collect1); Map<String, Long> collect2 = map.values() .stream() .map(Map::entrySet) .flatMap(Set::stream) .distinct() .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (f, n) -> n)); System.out.println("collect2 = " + collect2);
输出: map = {A={a=100, b=200, c=500}, B={a=100, b=200, c=800, d=1000}} collect = {a=200, b=400, c=1300, d=1000} collect1 = [a=100, b=200, c=500, c=800, d=1000] collect2 = {a=100, b=200, c=800, d=1000}
标签:map,Java,stream,Map,collect,param2,put From: https://www.cnblogs.com/bevis-byf/p/16952264.html