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 code for converting // Set to Stream 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+" ")); } } |
Example 2 : Converting HashSet of String to stream.
// Java code for converting // Set to Stream 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+" ")); } } |
Note : Objects that you insert in HashSet are not guaranteed to be inserted in same order. Objects are inserted based on their hash code.
Attention reader! Don’t stop learning now. Get hold of all the important Java and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready.
Recommended Posts:
- Character Stream Vs Byte Stream in Java
- Difference between Stream.of() and Arrays.stream() method in Java
- foreach() loop vs Stream foreach() vs Parallel Stream foreach()
- Convert Stream to Set in Java
- Program to convert a Set to Stream in Java using Generics
- Program to Convert List to Stream in Java
- Program to Convert Stream to an Array in Java
- Program to convert Boxed Array to Stream in Java
- Program to convert Primitive Array to Stream in Java
- Program to convert a Map to a Stream in Java
- Convert an Iterator to Stream in Java
- Convert an Iterable to Stream in Java
- How to convert a Stream into a Map in Java
- Java Stream | Collectors toCollection() in Java
- Stream In Java
- java.util.stream.IntStream/LongStream | Search an element
- stream.limit() method in Java
- Stream skip() method in Java with examples
- Stream.reduce() in Java with examples
- Stream.concat() in Java
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

