In this post, we’ll talk about the Collectors.toCollection() method in Java.

In the previous post, we have discussed toList(), and toSet() methods of the Collectors class. Both methods return 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 the 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 the 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 the desired type works similarly as List. In the following 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]

That’s all about the Collectors class toCollection() method in Java.