Convert stream to Set

This example will show how to convert a Stream into a Hashset using Java 8. A Collector is a reduction operation that will accumulate elements from a stream into a cumulative result. We must supply a Collector in order to gather all the Stream’s items in a Set which we can do by using a connivence method toSet() from the Collectors utility class.

@Test
public void stream_to_set() {

    Set<Integer> numbers = Stream.of(1, 2, 3)
            .collect(Collectors.toSet());

    assertTrue(numbers.size() == 3);
}

If you prefer, you could use a static import.

...
import static java.util.stream.Collectors.toSet;
...
@Test
public void stream_to_set() {

    Set<Integer> numbers = Stream.of(1, 2, 3)
            .collect(toSet());

    assertTrue(numbers.size() == 3);
}