Search code examples
javajava-8guavajava-stream

Java 8 Stream String Null Or Empty Filter


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?


Solution

  • 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.