Open In App

Java Stream | Collectors toCollection() in Java

Collectors toCollection(Supplier<C> collectionFactory) method in Java is used to create a Collection using Collector. It returns a Collector that accumulates the input elements into a new Collection, in the order in which they are passed.

Syntax:



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

where:-

Parameters: This method takes a mandatory parameter collectionFactory of type Supplier which returns a new, empty Collection of the appropriate type.



Return Value: This method returns a collector which collects all the input elements into a Collection, in encounter order.

Below given are some examples to illustrate the implementation of toCollection() in a better way:

Example 1:




// Java code to demonstrate Collectors
// toCollection(Supplier collectionFactory) method
  
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;
  
class GFG {
  
    // Driver code
    public static void main(String[] args)
    {
  
        // Creating a string stream
        Stream<String> s = Stream.of("Geeks", "for", "GeeksClasses");
  
        // Using toCollection() method
        // to create a collection
        Collection<String> names = s
                                       .collect(Collectors
                                                    .toCollection(TreeSet::new));
  
        // Printing the elements
        System.out.println(names);
    }
}

Output:
[Geeks, GeeksClasses, for]

Example 2:




// Java code to demonstrate Collectors
// toCollection(Supplier collectionFactory) method
  
import java.util.Collection;
import java.util.TreeSet;
import java.util.stream.Collectors;
import java.util.stream.Stream;
  
class GFG {
  
    // Driver code
    public static void main(String[] args)
    {
  
        // Creating a string stream
        Stream<String> s = Stream.of("2.5", "6", "4");
  
        // Using Collectors toCollection()
        Collection<String> names = s
                                       .collect(Collectors
                                                    .toCollection(TreeSet::new));
  
        // Printing the elements
        System.out.println(names);
    }
}

Output:
[2.5, 4, 6]

Article Tags :