Computer >> Computer tutorials >  >> Programming >> Java

Java Stream Collectors toCollection() in Java


The to Collection() method of the Collectors class in Java returns a Collector that accumulates the input elements into a new Collection in encounter order. The syntax is as follows −

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

Here, T - is the type of the input elements, C is the Type of the resulting Collection, Supplier is the supplier of results, and collection factory is the Supplier that returns a new, empty Collection of the appropriate type

Example

Let us now see an example −

import java.util.Collection;
import java.util.TreeSet;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class Demo {
   public static void main(String[] args) {
      Stream<String> stream = Stream.of("25", "10", "15", "20", "25");
      Collection<String> collection = stream.collect(Collectors.toCollection(TreeSet::new));
      System.out.println("Collection = "+collection);
   }
}

Output

Collection = [10, 15, 20, 25]

Example

Let us see another example −

import java.util.Collection;
import java.util.TreeSet;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class Demo {
   public static void main(String[] args) {
      Stream<String> stream = Stream.of("Jack", "Tom", "Brad", "Tim", "Kevin", "Bradley", "Ryan");
      Collection<String> collection = stream.collect(Collectors.toCollection(TreeSet::new));
      System.out.println("Collection = "+collection);
   }
}

Output

Collection = [Brad, Bradley, Jack, Kevin, Ryan, Tim, Tom]