Collectors.toSet() – Convert/collect a stream to Set

 342 total views,  2 views today

Welcome to Java 8 series. In this tutorial, you will learn about how to Convert/collect a stream to set using Collectors.toSet().

If you would like to learn more about Java Stream operations.Please check out this link.

In this example, we will use Stream.collect() operation to perform a reduce operation on the stream of elements.i.e., we will collect the stream of elements as a Set.

To use Collectors.toSet() in stream operations, we have to import Collectors package.

Collectors.toSet() example

Set interface is mainly used for avoiding duplicates and have only unique elements.We will be using Collectors.toSet() operation to convert/collect all elements from the stream and store it in a set.

import java.util.Arrays;
import java.util.List;
import java.util.Set;

public class StaticReference {
	public static void main(String[] args) {

		List<String> fruits = Arrays.asList("apple", 

		Set<String> collectedFruits =
				.map(eachFruit -> eachFruit.toUpperCase())




Hope you like this article. Thanks for reading and Please leave us a comment below!

Tags :

About the Author


Hey There, My name is Rajasekar and I am the author of this site. I hope you are liking my tutorials and references. Programming and learning new technologies are my passion. The ultimate idea of this site is to share my knowledge(I am still a learner :)) and help you out!. Please spread your words about us ( and give a thumbs up :) Feel free to contact me for any queries!.