Collectors toCollection(Supplier collectionFactory) example – Java 8 Streams

Collectors toCollection(Supplier<C> collectionFactory) 

Returns a Collector that accumulates the input elements into a new Collection, in encounter order. The Collection is created by the provided factory.

Collectors toCollection() Examples

Example 1

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
// author programtalk.com
public class CollectorsToCollectionExample {
  public static void main(String[] args) {
    List<String> list = Arrays.asList("Obama","Trump","Next");
    
    List<String> presidents = list.stream()
        .collect(Collectors.toCollection(ArrayList::new));

    presidents.forEach(System.out::println);
  }
}

Output is:

Obama
Trump
Next

Example 2 : Easy create a list and add one item

import java.util.ArrayList;
import java.util.stream.Collectors;
import java.util.stream.Stream;
// author programtalk.com
public class CollectorsToCollectionExample {
  public static void main(String[] args) {
    ArrayList<String> collect = Stream.of("hello").collect(Collectors.toCollection(ArrayList::new));
    collect.forEach(System.out::println);
  }
}

Output is:

hello
Like this post? Don’t forget to share it!

Leave a Reply

Your email address will not be published. Required fields are marked *