Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert Stream of Map into TreeMap in Java8

Tags:

java

java-8

I have a method that takes in a Stream of map and should return a TreeMap

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

How can I make it return a TreeMap?

like image 549
tintin Avatar asked Dec 19 '22 01:12

tintin


2 Answers

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));
like image 173
Louis Wasserman Avatar answered Dec 21 '22 15:12

Louis Wasserman


Incase you're using a 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 datatype you need as value in the tree map

This yields TreeMap<Integer, List>

like image 45
Sharan Arumugam Avatar answered Dec 21 '22 14:12

Sharan Arumugam