Java 8 – Convert Stream to LinkedHashSet

In this article, we will discuss how to convert Stream into a LinkedHashSet in Java 1.8 version using Stream API. LinkedHashSet doesn’t allow duplicates but maintains insertion-order.

Stream to LinkedHashSet :

  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 LinkedHashSet
  • For Set to LinkedHashSet conversion, create LinkedHashSet object and pass above set as constructor-argument
  • Finally, print converted LinkedHashSet elements to console

StreamToLinkedHashSetUsingCollectorsToSet.java

package net.bench.resources.stream.to.list;

import java.util.LinkedHashSet;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class StreamToLinkedHashSetUsingCollectorsToSet {

	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 LinkedHashSet<String>
		LinkedHashSet<String> lhSetNames = new LinkedHashSet<String>(names);


		// 4. print to console
		System.out.println("Stream to LinkedHashSet : \n\n" + lhSetNames);
	}
}

Output:

Stream to LinkedHashSet : 

[Lingaraj, Abdul, Rajiv, Anbu, Santosh]

2. Using Collectors.toCollection()

  • Convert Stream to LinkedHashSet using collect() method of Stream API by passing Collectors.toCollection(LinkedHashSet::new) as input argument directly
  • Print converted LinkedHashSet elements to console

StreamToLinkedHashSetUsingCollectorsToCollection.java

package net.bench.resources.stream.to.list;

import java.util.LinkedHashSet;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class StreamToLinkedHashSetUsingCollectorsToCollection {

	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 LinkedHashSet<String>
		LinkedHashSet<String> lhSetNames = nameStream
				.collect(Collectors.toCollection(LinkedHashSet::new));


		// 3. print to console
		System.out.println("Stream to LinkedHashSet : \n\n" + lhSetNames);
	}
}

Output:

Stream to LinkedHashSet : 

[Rajiv, Anbu, Santosh, Abdul, Lingaraj]

Related Articles:

References:

Happy Coding !!
Happy Learning !!

Java 8 - Convert Stream to TreeSet
Java 8 - Convert Stream to HashSet