A Stream in Java is used to process collections of data in a functional style. However, after performing stream operations, you often need to collect the processed elements into a Set to eliminate duplicates and store unique values. Java provides multiple ways to convert a Stream into a Set.
- Converts a Stream into a Set containing unique elements.
- Automatically removes duplicate values during collection.
- Supports collecting elements into different implementations such as HashSet, LinkedHashSet, and TreeSet.
Methods to Convert a Stream to a Set
Java provides the following ways to convert a Stream into a Set.
1. Convert a Stream to a Set Using Collectors.toSet()
The Collectors.toSet() method is the most commonly used way to collect stream elements into a Set. It automatically removes duplicate elements.
Syntax:
stream.collect(Collectors.toSet());
import java.util.*;
import java.util.stream.Stream;
import java.util.stream.Collectors;
class GFG {
// Driver code
public static void main(String[] args) {
// Creating a Stream of Integers
Stream<Integer> stream = Stream.of(-2, -1, 0, 1, 2);
// Using Stream.collect() to collect the
// elements of stream in a container.
Set<Integer> streamSet = stream.collect(Collectors.toSet());
// Displaying the elements
streamSet.forEach(num -> System.out.println(num));
}
}
Output
-1 0 -2 1 2
2. Convert a Stream to a Set Using Collectors.toCollection()
The Collectors.toCollection() method allows collecting stream elements into a specific Set implementation such as LinkedHashSet or TreeSet.
Syntax:
stream.collect(Collectors.toCollection(LinkedHashSet::new));
import java.util.*;
import java.util.stream.*;
class GFG {
public static void main(String[] args)
{
Stream<String> stream
= Stream.of("Java", "Python", "Java", "C++");
Set<String> set = stream.collect(
Collectors.toCollection(LinkedHashSet::new));
System.out.println(set);
}
}
Output
[Java, Python, C++]
3. Convert a Stream to an Unmodifiable Set Using Collectors.toUnmodifiableSet()
The Collectors.toUnmodifiableSet() method (introduced in Java 10) creates an immutable Set. Any attempt to modify the resulting set throws an UnsupportedOperationException.
Syntax:
stream.collect(Collectors.toUnmodifiableSet());
import java.util.*;
import java.util.stream.*;
class GFG {
public static void main(String[] args)
{
Stream<String> stream
= Stream.of("Java", "Python", "Java", "C++");
Set<String> set
= stream.collect(Collectors.toUnmodifiableSet());
System.out.println(set);
}
}
Output
[Java, Python, C++]
Benefits After Conversion
Converting a Stream to a Set is useful when only unique elements are required after performing stream operations. It also enables efficient searching and prevents duplicate entries in the resulting collection.
- Eliminates duplicate elements automatically.
- Provides efficient lookup operations.
- Supports different Set implementations based on ordering requirements.