This post will discuss toList(), toSet(), and toMap() methods of Collectors class in Java.

1. Using Collectors.toList() method

Collectors.toList() method returns a Collector which collects all the input elements into a new list. It doesn’t offer any guarantee on the type of list returned.

⮚ Get a list from the specified values

⮚ Convert a primitive array to a list

⮚ Convert a non-primitive array to a list

⮚ Convert string to list of Characters

 

Download  Run Code

2. Using Collectors.toSet() method

Collectors.toSet() method works in the similar way as Collectors.toList() but returns a set which discards the duplicates present in the input.

⮚ Get a set from specified values

⮚ Convert a primitive array to a set

⮚ Convert a non-primitive array to a set

Download  Run Code

3. Using Collectors.toMap() method

Since a stream is a sequence of items, to construct a map out of it, we need to specify how to extract keys/values pairs. The Collectors.toMap() returns a Collector that collects all the input elements into a new map by applying the specified mapping functions to the input elements, which help identify the keys and values.

 
If we want a map with different types for key and value, we can do something like :

 
Another approach to accommodate different types for keys and values is to use the AbstractMap.SimpleEntry<K,V> or AbstractMap.SimpleImmutableEntry<K,V>, which are just implementations of the Map.Entry<K,V> interface.

Download  Run Code

Output:

Sex is Male
Age is 26
Name is John

 
We can also use an overloaded version of the Collectors.toMap() method to specify the desired map type and how to deal with collisions between multiple values mapping to the same key.

Download  Run Code

Output:

Age is 26
Name is John
Sex is Male

 
This is equivalent to:

Download  Run Code

Output:

Age is 26
Name is John
Sex is Male

That’s all about the Collectors class in Java 8.