Skip to main content

Posts

Showing posts from October, 2021

Java Stream – Convert a Stream to Set

In this tutorial you’ll see how to convert a Stream to Set using collector method and utility methods like toSet() and toCollection() of Collectors class in Java Stream API . 1. A simple example to collect Stream elements into a HashSet. import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; public class StreamToSet { public static void main(String[] args) { Stream<String> streamElem = Stream.of("A", "B", "C", "D"); Set<String> setFromStream = streamElem.collect(Collectors.toSet()); // get type of object System.out.println(setFromStream.getClass().getName()); System.out.println("Elements in the Set- " + setFromStream); } } Output java.util.HashSet Elements in the Set- [A, B, C, D] As you can see type of the Set returned is java.util.HashSet. 2. If you want to convert the Stream into another implementation of Set say TreeSet then you can use Collectors.t