Conversion of Stream To Set in Java


We can convert a stream to set using the following ways.

  • Using stream.collect() with Collectors.toSet() method - Stream collect() method iterates its elements and stores them in a collection.collect(Collector.toSet()) method.

  • Using set.add() method - Iterate stream using forEach and then add each element to the set.

Example

Live Demo

import java.util.*;
import java.util.stream.Stream;
import java.util.stream.Collectors;
 
public class Tester {        
   public static void main(String[] args) {
      Stream<String> stream = Stream.of("a","b","c","d");

      // Method 1
      Set<String> set = stream.collect(Collectors.toSet());
      set.forEach(data -> System.out.print(data + " "));

      Stream<String> stream1 = Stream.of("a","b","c","d");
      System.out.println();
      //Method 2
      Set<String> set1 = new HashSet<>();
      stream1.forEach(set1::add);
      set1.forEach(data -> System.out.print(data + " "));
   }
}

Output

a b c d
a b c d

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 18-Jun-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements