Convert a Stream to a Set in Java
This post will discuss how to convert a stream to a set in Java.
1. Using Collectors
We can collect elements of a stream in a container using the Stream.collect() method, which accepts a Collector. We can pass the collector returned by Collectors.toSet() that accumulates the elements of the stream into a new Set. This is the standard way to convert a stream to a set in Java 8 and above.
|
1 2 3 |
Stream<Integer> stream = Stream.of(1, 2, 3, 4, 5); Set<Integer> set = stream.collect(Collectors.toSet()); System.out.println(set); |
But Collectors.toSet() doesn’t guarantee the type of the set returned. To have more control over the returned Set, we can use the Collectors.toCollection() method to accept a constructor reference to the desired Set.
|
1 2 3 |
Stream<Integer> stream = Stream.of(1, 2, 3, 4, 5); Set<Integer> set = stream.collect(Collectors.toCollection(HashSet::new)); System.out.println(set); |
2. Using Divide & Conquer
We can easily divide the problem into two parts:
|
1 2 3 4 5 6 7 |
Stream<Integer> stream = Stream.of(1, 2, 3, 4, 5); Integer[] lang = stream.toArray(Integer[]::new); Set<Integer> set = new HashSet<>(); Collections.addAll(set, lang); System.out.println(set); |
3. Using forEach() method
We can also loop through all elements of the stream using the forEach() method and use set.add() to add each element to an empty Set.
|
1 2 3 4 |
Stream<Integer> stream = Stream.of(1, 2, 3, 4, 5); Set<Integer> set = new HashSet<>(); stream.forEach(set::add); System.out.println(set); |
Please note that if the stream is parallel, elements may not be processed in original order with the forEach() method. We can use the forEachOrdered() method to preserve the original order, as shown below:
|
1 2 3 4 |
Stream<Integer> stream = Stream.of(1, 2, 3, 4, 5); Set<Integer> set = new HashSet<>(); stream.parallel().forEachOrdered(set::add); System.out.println(set); |
That’s all about converting Stream to a Set in Java.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)