Collectors toCollection(Supplier collectionFactory) example

Description

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 ww.ja v  a2 s.  c o 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.





















Home »
  Java Streams »
    Reference »




Collectors
DoubleStream
DoubleStream.Builder
IntStream
IntStream.Builder
LongStream
LongStream.Builder
Stream
Stream.Builder