Java 8 – Convert Stream to TreeMap

In this article, we will discuss how to convert Stream into a TreeMap in Java 1.8 version using Stream API

Stream to TreeMap :

Using Collectors.toMap() method, we can convert Stream into a Map. There are 2 variants of Collectors.toMap() method,

  1. Collectors.toMap(keyMapper, valueMapper, mergeFunction)
  2. Collectors.toMap(keyMapper, valueMapper, mergeFunction, supplier)

1. Using Collectors.toMap(keyMapper, valueMapper, mergeFunction)

  • First variant of Collectors.toMap() method accepts 3 input-arguments
    1. Key mapper – mapping function to produce keys
    2. Value mapper – mapping function to produce values
    3. Merge Function – this is used to resolve collisions between values associated with the same key
  • Above method helps to convert Stream into Map
  • For converting into TreeMap, create TreeMap object and pass above obtained Map as constructor-argument
  • TreeMap stores Key-Value pairs according to sorting order of Keys
  • Finally, print converted TreeMap pairs to console

StreamToMapUsingCollectorsToMap.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
package net.bench.resources.stream.to.treemap;
 
import java.util.TreeMap;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;
 
public class StreamToMapUsingCollectorsToMap {
 
    public static void main(String[] args) {
 
        // 1. Stream of String tokens
        Stream<String> nameStream = Stream.of(
                "Rajiv",
                "Anbu",
                "Santosh",
                "Abdul",
                "Lingaraj"
                );
 
 
        // 2. convert Stream<String> to Map<String, Integer>
        Map<String, Integer> map = nameStream
                .collect(Collectors.toMap(
                        Function.identity(), // 1. actual String as KEY
                        String::length,  // 2. String length as their VALUE
                        (key1, key2) -> key1) // 3. duplicate KEY resolver
                        );
 
 
        // 2.1 print to console
        System.out.println("1. Stream to Map conversion : \n\n" + map);
 
 
        // 3. convert Map to TreeMap using inter-conversion constructor
        TreeMap<String, Integer> tMap = new TreeMap<>(map);
 
 
        // 3.1 print to console
        System.out.println("\n\n2. Stream to TreeMap conversion : \n\n" + tMap);
    }
}

Output:

1
2
3
4
5
6
7
8
1. Stream to Map conversion :
 
{Lingaraj=8, Abdul=5, Rajiv=5, Santosh=7, Anbu=4}
 
 
2. Stream to TreeMap conversion :
 
{Abdul=5, Anbu=4, Lingaraj=8, Rajiv=5, Santosh=7}

2. Using Collectors.toMap(keyMapper, valueMapper, mergeFunction, supplier)

  • This is the 2nd variant of Collectors.toMap() method which accepts 4 input-arguments
    1. Key mapper – mapping function to produce keys
    2. Value mapper – mapping function to produce values
    3. Merge Function – this is used to resolve collisions between values associated with the same key
    4. Supplier – function which returns a new, empty Map into which the results will be inserted
  • Above method helps to convert Stream into HashMap, LinkedHashMap or TreeMap directly or whichever Supplier we pass as 4th argument
  • In the below example, we are passing TreeMap implementation class as method/constructor reference TreeMap::new
  • TreeMap stores Key-Value pairs according to sorting order of Keys
  • Finally, print converted TreeMap pairs to console

StreamToTreeMapUsingCollectorsToMap.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
package net.bench.resources.stream.to.treemap;
 
import java.util.TreeMap;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;
 
public class StreamToTreeMapUsingCollectorsToMap {
 
    public static void main(String[] args) {
 
        // 1. Stream of String tokens
        Stream<String> nameStream = Stream.of(
                "Rajiv",
                "Anbu",
                "Santosh",
                "Abdul",
                "Lingaraj"
                );
 
 
        // 2. convert Stream<String> to TreeMap<String, Integer>
        TreeMap<String, Integer> tMap = nameStream
                .collect(Collectors.toMap(
                        Function.identity(), // 1. actual String as KEY
                        String::length,  // 2. String length as their VALUE
                        (key1, key2) -> key1, // 3. duplicate KEY resolver
                        TreeMap::new // 4. implementation-class
                        ));
 
 
        // 2.1 print to console
        System.out.println("Stream to TreeMap conversion : \n\n" + tMap);
    }
}

Output:

1
2
3
Stream to TreeMap conversion :
 
{Abdul=5, Anbu=4, Lingaraj=8, Rajiv=5, Santosh=7}

Related Articles:

References :

Happy Coding !!
Happy Learning !!

Java 8 - Convert Stream to ConcurrentHashMap
Java 8 - Convert Stream to LinkedHashMap