What is Collectors.toCollection() in Java?

What is the collectors class?

Collectors is a utility class that provides various implementations of reduction operations, such as grouping elements, adding elements to different collections, summarizing elements according to various criteria, and so on. The other functionalities in the Collectors class are usually used as the final operation on streams.

The toCollection() method

toCollection() is a static method of the Collectors class, which is used to collect/accumulate all the elements in a new collection in the encountered order.

The toCollection method is defined in the Collectors class. The Collectors class is defined in the java.util.stream package. To import the Collectors class, we check the following import statement:

import java.util.stream.Collectors;

Syntax


public static <T, C extends Collection<T>> Collector<T, ?, C> toCollection(Supplier<C> collectionFactory)

Parameters

  • Supplier<C> collectionFactory: The Supplier implementation provides a new empty Collection into which the elements/results are inserted.

Return value

This method returns a Collector that collects all the elements to a collection.

Code example

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class Main {
public static void main(String[] args)
{
List<String> stringList = Arrays.asList("educative", "io", "edpresso");
System.out.println("Stream before modification - " + stringList);
Stream<String> stringStream = stringList.stream();
List<String> uppercaseStream = stringStream.map(String::toUpperCase).collect(Collectors.toCollection(ArrayList::new));
System.out.println("Stream after modification - " + uppercaseStream);
}
}

Code explanation

  • Lines 1–4: We import the relevant packages.
  • Line 10: We define a list of strings called stringList.
  • Line 12: We print the stringList.
  • Line 14: We create a stream out of the stringList.
  • Line 16: We convert the stream elements to uppercase, using the map method and collect the resulting elements to a new ArrayList with the toCollection method.
  • Line 18: We print the new list of uppercase elements.

Note: Refer to the “What is an ArrayList in Java?” shot to learn more about an ArrayList.