我有一个方法,它接收一个地图流,应该返回一个TreeMap
public TreeMap<String, String> buildTreeMap(Stream<Map<String, String>> inStream) {
return stream.collect(toMap(???));
}
Run Code Online (Sandbox Code Playgroud)
如何让它返回TreeMap?
小智 6
如果您使用的是groupingBy,
stream()
.collect(
Collectors.groupingBy(
e -> e.hashCode(), TreeMap::new, Collectors.toList()))
Run Code Online (Sandbox Code Playgroud)
其中e -> e.hashCode
关键函数是Entry::getKey
,Student::getId
是Collectors.toList()
,即您需要downstream
什么数据类型作为树形图中的值
这产生TreeMap<Integer, List>
stream.collect(TreeMap::new, TreeMap::putAll,
(map1, map2) -> { map1.putAll(map2); return map1; });
Run Code Online (Sandbox Code Playgroud)
...假设您想将所有地图组合成一个大地图.
如果您需要不同的语义来合并相同键的值,请执行类似的操作
stream.flatMap(map -> map.entrySet().stream())
.collect(toMap(
Entry::getKey, Entry::getValue, (v1, v2) -> merge(v1, v2), TreeMap::new));
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
9024 次 |
最近记录: |