Distinct elements in Java 8 streams

Finding the distinct elements of a Java stream is easy. We can use the distinct method:

List<String> words = Arrays.asList("hello", "Java8", "world!", "hello);
List<String> distinctWords = words.stream()
        .collect(Collectors.toList()); // ["hello", "Java8", "world!"]
Finding the distinct elements in a Java 8 stream using the stream.distinct() method.

The first part of the code example filters the non-empty strings and counts them. The second part of filters and counts the empty strings.

Subscribe to Java 8 Resources

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.