Java 8 流字符串空或空过滤器

2022-01-22 00:00:00 java-8 java java-stream guava

我在 Stream 中有 Google Guava:

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(","))

如您所见,过滤器函数中有一个语句 !String.isNullOrEmpty(entity).

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

我不想在项目中再使用 Guava,所以我只想简单地替换它:

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?

推荐答案

你可以自己写谓词:

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

然后只需使用 valueNotNullOrEmpty 作为您的过滤器参数.

Then just use valueNotNullOrEmpty as your filter argument.

相关文章