Convert Stream to Set using Stream collect(toSet())

Stream collect()

Stream collect() method collects elements from a stream and stores them in a collection.

We can supply a Collector to the collect method to accumulate the Stream elements into new Set.

collect(Collector.toSet()) collects elements from a stream to a Set.
 
convert stream to set

Example : Convert stream to a set

package com.topjavatutorial.java8examples;

import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class StreamOperations {

  public static void main(String[] args) {
    Set<Integer> collected = Stream.of(1,2,3,4,5)
        .collect(Collectors.toSet());
    collected.forEach(System.out::println);
  }

}

Output:

1
2
3
4
5

 

We can also add a static import for Collectors.toSet and rewrite the code as :

package com.topjavatutorial.java8examples;

import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import static java.util.stream.Collectors.toSet;

public class StreamOperations {

  public static void main(String[] args) {
    Set<Integer> collected = Stream.of(1,2,3,4,5)
        .collect(toSet());
    collected.forEach(System.out::println);
    
  }

}


 

Example : Convert Stream to TreeSet using collect(Collector.toCollection())

This example uses Collectors.toCollection() with collect() to convert a stream to TreeSet.

Set<Integer> collected = Stream.of(1,2,3,4,5)
    .collect(Collectors.toCollection(TreeSet::new));
collected.forEach(System.out::println);

Output:

1
2
3
4
5

 

© 2016, https:. All rights reserved. On republishing this post, you must provide link to original post

You may also like...

Leave a Reply.. code can be added in <code> </code> tags