Java 8 Stream String Null Or Empty Filter

ServerSideCat picture ServerSideCat · Jul 13, 2015 · Viewed 60.2k times · Source

I've got Google Guava inside Stream:

this.map.entrySet().stream()
.filter(entity -> !Strings.isNullOrEmpty(entity.getValue()))
.map(obj -> String.format("%s=%s", obj.getKey(), obj.getValue()))
.collect(Collectors.joining(","))

As you see there is a statement !String.isNullOrEmpty(entity) inside the filter function.

I don't want to use Guava anymore in the project, so I just want to replace it simply by:

string == null || string.length() == 0;

How can I do it more elegant?

Answer

fge picture fge · Jul 13, 2015

You can write your own predicate:

final Predicate<Map.Entry<?, String>> valueNotNullOrEmpty
    = e -> e.getValue() != null && !e.getValue().isEmpty();

Then just use valueNotNullOrEmpty as your filter argument.