Filter Java 8 stream

Let's filter a list of strings using Java 8 streams:

List<String> list = Arrays.asList("a", "", "b", "", "c");
 
// Count the non-empty strings
long nonEmptyCount = list.stream()
        .filter(x -> !x.isEmpty())
        .count(); // 3
 
// Count the empty strings
long emptyCount = list.stream()
        .filter(String::isEmpty) // same as .filter(x -> x.isEmpty())
        .count(); // 2
Example of filtering Java 8 streams using the stream.filter() 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.
jamie@example.com
Subscribe