在创建映射之前,不能避免将值收集到映射中
LinkedHashMap
分页装订器
Map<String, Map<String, Long>> organizationApps = input.stream()
.flatMap(e -> e.entrySet().stream())
.collect(groupingBy(Map.Entry::getKey, Collector.of(HashMap::new,
(r, t) -> t.getValue().forEach((k, v) -> r.merge(k, v, Long::sum)),
(r1, r2) -> {
r2.forEach((v1, v2) -> r1.merge(v1, v2, Long::sum));
return r1;
},
(Map<String, Long> m) -> m.entrySet().stream()
.sorted(Collections.reverseOrder(Map.Entry.comparingByValue()))
.collect(toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e2,
LinkedHashMap::new))
)));
相当于下面的(Java9+)代码
Map<String, Map<String, Long>> organizationApps = input.stream()
.flatMap(m -> m.entrySet().stream())
.collect(groupingBy(Map.Entry::getKey, collectingAndThen(flatMapping(
t -> t.getValue().entrySet().stream(),
toMap(Map.Entry::getKey, Map.Entry::getValue, Long::sum)),
(Map<String, Long> m) -> m.entrySet().stream()
.sorted(Collections.reverseOrder(Map.Entry.comparingByValue()))
.collect(toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e2,
LinkedHashMap::new))
)));
结束时
this answer
flatMapping
收集器,但您的自定义收集器也会完成此工作。