In this article, we will discuss how to convert Stream into a HashSet in Java 1.8 version using Stream API. Unlike List, Set neither allows duplicates nor maintains order.
Stream to HashSet :
- Using Collectors.toSet()
- Using Collectors.toCollection()
1. Using Collectors.toSet()
- First, convert Stream to Set using collect() method of Stream API by passing Collectors.toSet() as input argument
- Above conversion yields Set and not HashSet
- For Set to HashSet conversion, create HashSet object and pass above set as constructor-argument
- Finally, print converted HashSet elements to console
StreamToHashSetUsingCollectorsToSet.java
package net.bench.resources.stream.to.list;
import java.util.HashSet;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class StreamToHashSetUsingCollectorsToSet {
public static void main(String[] args) {
// 1. Stream of String tokens
Stream<String> nameStream = Stream.of(
"Rajiv",
"Anbu",
"Santosh",
"Abdul",
"Lingaraj"
);
// 2. convert Stream<String> to Set<String>
Set<String> names = nameStream.collect(Collectors.toSet());
// 3. Set<String> to HashSet<String>
HashSet<String> hSetNames = new HashSet<String>(names);
// 4. print to console
System.out.println("Stream to HashSet : \n\n" + hSetNames);
}
}
Output:
Stream to HashSet :
[Lingaraj, Abdul, Rajiv, Anbu, Santosh]
2. Using Collectors.toCollection()
- Convert Stream to HashSet using collect() method of Stream API by passing Collectors.toCollection(HashSet::new) as input argument directly
- Print converted HashSet elements to console
StreamToHashSetUsingCollectorsToCollection.java
package net.bench.resources.stream.to.list;
import java.util.HashSet;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class StreamToHashSetUsingCollectorsToCollection {
public static void main(String[] args) {
// 1. Stream of String tokens
Stream<String> nameStream = Stream.of(
"Rajiv",
"Anbu",
"Santosh",
"Abdul",
"Lingaraj"
);
// 2. convert Stream<String> to HashSet<String>
HashSet<String> hSetNames = nameStream
.collect(Collectors.toCollection(HashSet::new));
// 3. print to console
System.out.println("Stream to HashSet : \n\n" + hSetNames);
}
}
Output:
Stream to HashSet :
[Lingaraj, Abdul, Rajiv, Anbu, Santosh]
Related Articles:
- Java 8 – Conversion of Arrays to Stream
- Java 8 – Conversion of Stream to Arrays
- Java 8 – Convert List to Stream
- Java 8 – Convert Stream to List
- Java 8 – Convert Stream to ArrayList
- Java 8 – Convert Stream to LinkedList
- Java 8 – Convert Stream to HashSet
- Java 8 – Convert Stream to LinkedHashSet
- Java 8 – Convert Stream to TreeSet
References:
- https://docs.oracle.com/javase/8/docs/api/java/util/stream/Collectors.html#toSet–
- https://docs.oracle.com/javase/8/docs/api/java/util/stream/Collectors.html#toCollection-java.util.function.Supplier-
Happy Coding !!
Happy Learning !!