I have a method that takes in a Stream of map and should return a TreeMap
public TreeMap buildTreeMap(Stream> inStream) {
return stream.collect(toMap(???));
}
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));