如何在Java8中将Map流转换为TreeMap [英] How to convert Stream of Map into TreeMap in Java8
本文介绍了如何在Java8中将Map流转换为TreeMap的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个接收地图流的方法,应该返回一个TreeMap
I have a method that takes in a Stream of map and should return a TreeMap
public TreeMap<String, String> buildTreeMap(Stream<Map<String, String>> inStream) {
return stream.collect(toMap(???));
}
如何让它返回TreeMap?
How can I make it return a TreeMap?
推荐答案
stream.collect(TreeMap::new, TreeMap::putAll,
(map1, map2) -> { map1.putAll(map2); return map1; });
...假设您想将所有地图合并为一张大地图。
...assuming you want to combine all the maps into one big map.
如果您想要为同一个键合并值的语义不同,请执行以下操作:
If you want different semantics for merging values for the same key, do something like
stream.flatMap(map -> map.entrySet().stream())
.collect(toMap(
Entry::getKey, Entry::getValue, (v1, v2) -> merge(v1, v2), TreeMap::new));
这篇关于如何在Java8中将Map流转换为TreeMap的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文