Conversion of Stream To Set in Java

Object Oriented ProgrammingJava Programming Java8

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
raja
Published on 23-Jul-2018 12:08:33
Advertisements