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!

3 Comments

  1. localizacion gps

    We’re a bunch of volunteers and starting a new scheme in our community.
    Your website provided us with useful info to work on. You’ve performed a
    formidable job and our whole neighborhood will probably
    be grateful to you.

  2. However, to date, betting on the Internet is still dominated by men. Apart from this plan, you can also stick to the common strategy that is certainly to play more number of
    times. The company is advised to come in large number and play the
    games and if they are lucky they’re able to win for the children a
    few of the a variety of games, which could bring to the clients some of the multiple
    games.
    슬롯게임 https://trpz.org/onlinebaccarat/

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.