Set is a collection that stores unique elements without allowing duplicates. Since the Set interface extends the Collection interface, it inherits the stream() method, which can be used to convert a set into a sequential Stream for functional-style data processing.
- Converts a Set into a Stream for functional programming operations.
- Enables operations such as filter(), map(), sorted(), reduce(), and collect().
- Supports both sequential and parallel stream processing.
Steps to convert a Set into a Stream
- Create a Set containing the required elements.
- Call the stream() method on the set.
- Store the returned stream in a Stream object.
- Perform Stream API operations such as forEach(), filter(), or map().
Example Using Integer Set To Convert to a Stream Using stream()
The stream() method, inherited from the Collection interface, returns a sequential stream containing the elements of the set
import java.util.*;
import java.util.stream.Stream;
class GFG {
// Driver code
public static void main(String[] args) {
// Creating an Integer HashSet
Set<Integer> set = new HashSet<>();
// adding elements in set
set.add(2);
set.add(4);
set.add(6);
set.add(8);
set.add(10);
set.add(12);
// converting Set to Stream
Stream<Integer> stream = set.stream();
// displaying elements of Stream using lambda expression
stream.forEach(elem->System.out.print(elem+" "));
}
}
Output:
2 4 6 8 10 12 Example Using String Set To Convert to a Stream Using stream()
The following example demonstrates how a HashSet of strings can be converted into a stream and its elements displayed.
import java.util.*;
import java.util.stream.Stream;
class GFG {
// Driver code
public static void main(String[] args) {
// Creating an String HashSet
Set<String> set = new HashSet<>();
// adding elements in set
set.add("Geeks");
set.add("for");
set.add("GeeksQuiz");
set.add("GeeksforGeeks");
// converting Set to Stream
Stream<String> stream = set.stream();
// displaying elements of Stream
stream.forEach(elem -> System.out.print(elem+" "));
}
}
Output
GeeksforGeeks Geeks for GeeksQuiz
Benefits After Conversion
Converting a Set to a Stream allows developers to perform complex data processing using the Java Stream API instead of manually iterating through the elements.
- Reduces boilerplate code by eliminating explicit iteration.
- Enables chaining of multiple stream operations.