Java 8 – Convert Stream to HashSet

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 :

  1. Using Collectors.toSet()
  2. 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:

References:

Happy Coding !!
Happy Learning !!

Java 8 - Convert Stream to LinkedHashSet
Java 8 - Convert Stream to LinkedList