Collectors Class in Java 8 – toList(), toSet() and toMap() methods

In this post, we will discuss about toList(), toSet() and toMap() methods of Collectors class in Java 8.

 

1. Collectors.toList()

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 the List returned.

 

1. Get a List from the specified values

 

 

2. Convert a primitive array to a List

 

 

3. Convert a non-primitive array to a List

 

 

4. Convert String to List of Characters

 

 

Download   Run Code

 

2.Collectors.toSet()

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

 

1. Get a Set from specified values

 

 

2. Convert a primitive array to a Set

 

 

3. Convert a non-primitive array to a Set

 

 

Download   Run Code

 

3.Collectors.toMap()

Since Stream is a sequence of items, in order to construct a Map out of it, we need specify how to extract keys/values pairs from it. 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 in identifying 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 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 where we can specify the desired Map type and the way 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

 
Thanks for reading.

Please use our online compiler to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 



Leave a Reply

avatar
  Subscribe  
Notify of