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.
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;
public static <T, C extends Collection<T>> Collector<T, ?, C> toCollection(Supplier<C> collectionFactory)
Supplier<C> collectionFactory
: The Supplier
implementation provides a new empty Collection
into which the elements/results are inserted.This method returns a Collector
that collects all the elements to a collection.
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);}}
stringList
.stringList
.stringList
.map
method and collect the resulting elements to a new ArrayList
with the toCollection
method.Note: Refer to the “What is an ArrayList in Java?” shot to learn more about an ArrayList.