Convert Stream to Set in Java

Java 8Object Oriented ProgrammingProgramming

At first, set a stream −

Stream<Integer> stream = Stream.of(25, 30, 45, 50, 75, 100, 125, 150);

Now, declare a Set and convert this stream to set −

Set<Integer> set = new HashSet<>();
stream.forEach(set::add);
set.forEach(res -> System.out.println(res));

Example

Following is the program to convert Stream to Set in Java −

import java.util.*;
import java.util.stream.*;
public class Demo {
   public static void main(String[] args) {
      Stream<Integer> stream = Stream.of(25, 30, 45, 50, 75, 100, 125, 150);
      Set<Integer> set = new HashSet<>();
      stream.forEach(set::add);
      System.out.println("Stream to Set...");
      set.forEach(res -> System.out.println(res));
   }
}

Output

Stream to Set...
50
100
150
25
75
45
125
30
raja
Published on 25-Sep-2019 11:28:01
Advertisements