Collectors toCollection() method in Java

In this post, we will talk about Collectors toCollection() method in Java.


 

In the previous post, we have discussed about toList(), and toSet() methods of the Collectors class. Both methods returns a Collector to collect the input elements into a new List or a Set, but doesn’t offer any guarantee on the type of the Collection returned. For instance, Collectors.toList() method can return an ArrayList or a LinkedList or any other implementation of the List interface.

 
To get the desired Collection, we can use toCollection() method provided by the Collectors class.

 

1. Get the Desired List Type:

The idea is to use the collector returned by Collectors.toCollection() method that can accept desired constructor method reference like ArrayList::new or LinkedList::new.

 

Download   Run Code

Output:

Array List is [2, 4, 6, 8, 10]
Linked List is [1, 3, 5, 7, 9]

 

We can also use toCollection() method to add elements of a Stream to an existing List (or a Set) as shown below:

 

Download   Run Code

Output:

[1, 2, 3, 4, 5]

 

2. Get the Desired Set Type:

Creating a new Set of desired type works in similar way as List. In below program, we pass method reference of HashSet::new and TreeSet::new to get a HashSet and a TreeSet respectively.

 

Download   Run Code

Output:

Hash Set is [2, 4, 6, 8, 10]
Tree Set is [1, 3, 5, 7, 9]

 

 
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