Below given are some methods which can be used to convert Stream to Set in Java.
Method 1 : Using Collectors
Stream collect() method takes elements from a stream and stores them in a collection.collect(Collector.toSet()) collects elements from a stream to a Set.
Stream.collect() method can be used to collect elements of a stream in a container. The Collector which is returned by Collectors.toSet() can be passed that accumulates the elements of stream into a new Set.
import java.util.*;
import java.util.stream.Stream;
import java.util.stream.Collectors;
class GFG {
public static void main(String[] args) {
Stream<Integer> stream = Stream.of(- 2 , - 1 , 0 , 1 , 2 );
Set<Integer> streamSet = stream.collect(Collectors.toSet());
streamSet.forEach(num -> System.out.println(num));
}
}
|
Method 2 : Converting Stream to Array and then to Set
The problem of converting Stream into Set can be divided into two parts :
1) Convert Stream to an Array
2) Convert Array to a Set
import java.util.*;
import java.util.stream.Stream;
import java.util.stream.Collectors;
class GFG {
public static void main(String[] args) {
Stream<String> stream = Stream.of( "G" , "E" , "K" , "S" );
String[] arr = stream.toArray(String[] :: new );
Set<String> set = new HashSet<>();
Collections.addAll(set,arr);
set.forEach(str -> System.out.println(str));
}
}
|
Note : Output is random because HashSet takes input in random order as generated hash value.
Method 3 : Using forEach
Stream can be converted into Set using forEach(). Loop through all elements of the stream using forEach() method and then use set.add() to add each elements into an empty set.
import java.util.*;
import java.util.stream.Stream;
import java.util.stream.Collectors;
class GFG {
public static void main(String[] args) {
Stream<Integer> stream = Stream.of( 5 , 10 , 15 , 20 , 25 );
Set<Integer> set = new HashSet<>();
stream.forEach(set::add);
set.forEach(num -> System.out.println(num));
}
}
|
Note : If Stream is parallel, then elements may not be processed in original order using forEach() method. To preserve the original order, forEachOrdered() method is used.
Convert a Set to Stream in Java