Java 8 – Convert Stream to TreeSet

In this article, we will discuss how to convert Stream into a TreeSet in Java 1.8 version using Stream API. TreeSet doesn’t allow duplicates but maintains sorting order either in natural/reverse order.

Stream to TreeSet :

  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 TreeSet
  • For Set to TreeSet conversion, create TreeSet object and pass above set as constructor-argument and this will conversion stores elements in alphabetical order
  • Finally, print converted TreeSet elements to console

StreamToTreeSetUsingCollectorsToSet.java

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

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

public class StreamToTreeSetUsingCollectorsToSet {

	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 TreeSet<String>
		TreeSet<String> tSetNames = new TreeSet<String>(names);


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

Output:

Stream to TreeSet : 

[Abdul, Anbu, Lingaraj, Rajiv, Santosh]

2. Using Collectors.toCollection()

  • Convert Stream to TreeSet using collect() method of Stream API by passing Collectors.toCollection(TreeSet::new) as input argument directly
  • This direct conversion stores elements in alphabetical order
  • Print converted TreeSet elements to console

StreamToHashSetUsingCollectorsToCollection.java

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

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

public class StreamToTreeSetUsingCollectorsToCollection {

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


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

Output:

Stream to TreeSet : 

[Abdul, Anbu, Lingaraj, Rajiv, Santosh]

References:

Happy Coding !!
Happy Learning !!

Java 8 - Convert Stream to HashMap
Java 8 - Convert Stream to LinkedHashSet