Java Streams - Collectors toCollection(Supplier collectionFactory) example








Collectors toCollection(Supplier<C> collectionFactory) returns a Collector that accumulates the input elements into a new Collection, in encounter order.

Syntax

toCollection has the following syntax.

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

Example

The following example shows how to use toCollection.

import java.util.Collection;
import java.util.TreeSet;
import java.util.stream.Collectors;
import java.util.stream.Stream;
//from  w  w  w  .  j a  v  a2  s .  co  m
public class Main {
  public static void main(String[] args) {
    Stream<String> s = Stream.of("a","b","c");
    
    Collection<String> names = s
        .collect(Collectors.toCollection(TreeSet::new));

    System.out.println(names);
  }
}

The code above generates the following result.