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

我有一个方法,它接收一个地图流,应该返回一个TreeMap

public TreeMap buildTreeMap(Stream<Map> inStream) { return stream.collect(toMap(???)); } 

如何让它返回TreeMap?

 stream.collect(TreeMap::new, TreeMap::putAll, (map1, map2) -> { map1.putAll(map2); return map1; }); 

…假设您想将所有地图组合成一个大地图。

如果您需要不同的语义来合并同一个键的值,请执行类似的操作

 stream.flatMap(map -> map.entrySet().stream()) .collect(toMap( Entry::getKey, Entry::getValue, (v1, v2) -> merge(v1, v2), TreeMap::new)); 

如果你正在使用groupingBy

  stream() .collect( Collectors.groupingBy( e -> e.hashCode(), TreeMap::new, Collectors.toList())) 

其中e -> e.hashCode是关键函数,如Entry::getKeyStudent::getIdCollectors.toList()downstream即树形图中需要什么数据类型作为

这会产生TreeMap