Convert a Set to Stream in Java
Last Updated :
11 Nov, 2022
Set interface extends Collection interface and Collection has stream() method that returns a sequential stream of the collection. Below given are some examples to understand the implementation in a better way. Example 1 : Converting Integer HashSet to Stream of Integers.
Java
import java.util.*;
import java.util.stream.Stream;
class GFG {
public static void main(String[] args) {
Set<Integer> set = new HashSet<>();
set.add( 2 );
set.add( 4 );
set.add( 6 );
set.add( 8 );
set.add( 10 );
set.add( 12 );
Stream<Integer> stream = set.stream();
stream.forEach(elem->System.out.print(elem+" "));
}
}
|
Output:
2 4 6 8 10 12
Example 2 : Converting HashSet of String to stream.
Java
import java.util.*;
import java.util.stream.Stream;
class GFG {
public static void main(String[] args) {
Set<String> set = new HashSet<>();
set.add("Geeks");
set.add(" for ");
set.add("GeeksQuiz");
set.add("GeeksforGeeks");
Stream<String> stream = set.stream();
stream.forEach(elem -> System.out.print(elem+" "));
}
}
|
Output:
GeeksforGeeks Geeks for GeeksQuiz
Note : Objects that you insert in HashSet are not guaranteed to be inserted in same order. Objects are inserted based on their hash code. Convert Stream to Set in Java
Share your thoughts in the comments
Please Login to comment...