Last Updated : 11 Jul, 2025
Java Setis a part of java.util package and extends java.util.Collection interface. It does not allow the use of duplicate elements and at max can accommodate only one null element. A
Streamis a sequence of objects that supports various methods which can be pipelined to produce the desired result. Below are the various methods to convert
Set to Stream.
// Java Program to convert
// Set to Stream in Java 8
import java.util.*;
import java.util.stream.*;
import java.util.function.*;
class GFG {
// Generic function to convert a set to stream
private static <T> Stream<T> convertSetToStream(Set<T> set)
{
return set.stream();
}
// Main method
public static void main(String args[])
{
// Create a set of String
Set<Integer> setOfInteger = new HashSet<>(
Arrays.asList(2, 4, 6, 8, 10));
// Print the set of Integer
System.out.println("Set of Integer: " + setOfInteger);
// Convert Set of Stream
Stream<Integer>
streamOfInteger = convertSetToStream(setOfInteger);
// Print the Stream of Integer
System.out.println("Stream of Integer: "
+ Arrays.toString(
streamOfInteger.toArray()));
}
}
Output:
Set of Integer: [2, 4, 6, 8, 10] Stream of Integer: [2, 4, 6, 8, 10]
// Java Program to convert
// Set to Stream in Java 8
import java.util.*;
import java.util.stream.*;
import java.util.function.*;
class GFG {
// Generic function to convert a set to stream
private static <T> Stream<T>
convertSetToStream(Set<T> set, Predicate<T> predicate)
{
return set.stream()
.filter(predicate);
}
// Main method
public static void main(String args[])
{
// Create a set of String
Set<String>
setOfString = new HashSet<>(
Arrays.asList("GeeksForGeeks",
"A computer portal",
"for",
"Geeks"));
// Print the set of String
System.out.println("Set of String: " + setOfString);
// Create the predicate for item starting with G
Predicate<String> predicate = new Predicate<String>() {
@Override
public boolean test(String s)
{
// filter items that start with "G"
return s.startsWith("G");
}
};
// Convert Set of Stream
Stream<String>
streamOfString = convertSetToStream(setOfString, predicate);
// Print the filter Stream of String
System.out.println("Stream from List with items"
+ " starting with G: ");
System.out.println(Arrays.toString(
streamOfString.toArray()));
}
}
Output:
Set of String: [for, Geeks, GeeksForGeeks, A computer portal] Stream from List with items starting with G: [Geeks, GeeksForGeeks]
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4