Below given are some methods which can be used to convert Stream to Set in Java.
Method 1 : Using Collectors
Stream collect() method takes elements from a stream and stores them in a collection.collect(Collector.toSet()) collects elements from a stream to a Set.
Stream.collect() method can be used to collect elements of a stream in a container. The Collector which is returned by Collectors.toSet() can be passed that accumulates the elements of stream into a new Set.
-1 0 -2 1 2
Method 2 : Converting Stream to Array and then to Set
The problem of converting Stream into Set can be divided into two parts :
1) Convert Stream to an Array 2) Convert Array to a Set
S E G K
Note : Output is random because HashSet takes input in random order as generated hash value.
Method 3 : Using forEach
20 5 25 10 15
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.
- 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 a Set to Stream 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 email@example.com. 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.