Finding the distinct elements of a Java stream is easy. We can use the Stream#distinct
method:
List<String> words = Arrays.asList("hello", "Java8", "world!", "hello");
List<String> distinctWords = words.stream()
.distinct()
.collect(Collectors.toList()); // ["hello", "Java8", "world!"]
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.