java 如何在Java8中将Map的Stream转换为TreeMap
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31660900/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to convert Stream of Map into TreeMap in Java8
提问by tintin
I have a method that takes in a Stream of map and should return a TreeMap
我有一个方法,它接受一个地图流并且应该返回一个 TreeMap
public TreeMap<String, String> buildTreeMap(Stream<Map<String, String>> inStream) {
return stream.collect(toMap(???));
}
How can I make it return a TreeMap?
我怎样才能让它返回一个TreeMap?
回答by Louis Wasserman
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));
回答by Sharan Arumugam
Incase you're using a groupingBy,
如果您使用的是groupingBy,
stream()
.collect(
Collectors.groupingBy(
e -> e.hashCode(), TreeMap::new, Collectors.toList()))
where e -> e.hashCode
is key function like Entry::getKey
, Student::getId
and Collectors.toList()
is downstream
i.e what datatypeyou need as valuein the tree map
这里e -> e.hashCode
就像是关键功能Entry::getKey
,Student::getId
而且Collectors.toList()
是downstream
即什么样的数据类型,你需要为价值树地图
This yields TreeMap<Integer, List>
这产生 TreeMap<Integer, List>