Friday, September 5, 2025
HomeLanguagesJavaConvert a Set to Stream in Java

Convert a Set to Stream in Java

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




// 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+" "));
     
    }
}


Output:

2 4 6 8 10 12 

Example 2 : Converting HashSet of String to stream. 

Java




// 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("Lazyroar");
     
    // converting Set to Stream
    Stream<String> stream = set.stream();
     
    // displaying elements of Stream
    stream.forEach(elem -> System.out.print(elem+" "));
     
    }
}


Output:

Lazyroar 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

RELATED ARTICLES

Most Popular

Dominic
32264 POSTS0 COMMENTS
Milvus
81 POSTS0 COMMENTS
Nango Kala
6634 POSTS0 COMMENTS
Nicole Veronica
11801 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11860 POSTS0 COMMENTS
Shaida Kate Naidoo
6749 POSTS0 COMMENTS
Ted Musemwa
7025 POSTS0 COMMENTS
Thapelo Manthata
6698 POSTS0 COMMENTS
Umr Jansen
6718 POSTS0 COMMENTS