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

<br />
import java.util.ArrayList;<br />
import java.util.Arrays;<br />
import java.util.List;<br />
import java.util.stream.Collectors;<br />
// author programtalk.com<br />
public class CollectorsToCollectionExample {<br />
  public static void main(String[] args) {<br />
    List&lt;String&gt; list = Arrays.asList(&quot;Obama&quot;,&quot;Trump&quot;,&quot;Next&quot;);</p>
<p>    List&lt;String&gt; presidents = list.stream()<br />
        .collect(Collectors.toCollection(ArrayList::new));</p>
<p>    presidents.forEach(System.out::println);<br />
  }<br />
}<br />

Output is:

<br />
Obama<br />
Trump<br />
Next<br />

Example 2 : Easy create a list and add one item

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

Output is:

<br />
hello<br />

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

4 Comments

  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.

  2. 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.

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.