如何在Java8中将Map流转换为TreeMap

tin*_*tin 3 java java-8

我有一个方法,它接收一个地图流,应该返回一个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::getKeyStudent::getIdCollectors.toList(),即您需要downstream 什么数据类型作为树形图中的

这产生TreeMap<Integer, List>


Lou*_*man 5

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)

  • 应该提到的是,这只是在重复键的情况下覆盖值. (4认同)