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!

One Comment

  1. Hello I am so thrilled I found your web site, I really found you
    by mistake, while I was researching on Yahoo for
    something else, Regardless I am here now and would just like to say thanks a lot for a marvelous
    post and a all round exciting blog (I also love the theme/design), I don’t have time to
    browse it all at the minute but I have bookmarked it and also added in your RSS feeds,
    so when I have time I will be back to read much more, Please do keep up the fantastic work.

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.