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

 215 total views,  1 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.

java.util.stream.Collectors

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;
import java.util.stream.Collectors;

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

		List<String> fruits = Arrays.asList("apple", 
				"mango", 
				"pomo", 
				"banana", 
				"orange", 
				"apple", 
				"banana");

		Set<String> collectedFruits = fruits.stream()
				.map(eachFruit -> eachFruit.toUpperCase())
				.collect(Collectors.toSet());

                collectedFruits.forEach(System.out::println);
	}
}

Output

APPLE
POMO
MANGO
BANANA
ORANGE

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

Tags :

About the Author

Rajasekar

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 (staticreference.com) and give a thumbs up :) Feel free to contact me for any queries!.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.