在Stream中过滤Null项

Bor*_*ijk 11 java null java-8 java-stream

使用Java Stream时,映射后有时会出现空值.目前,当需要省略这些值时,我使用:

.stream()
.<other operations...>
.filter(element -> element != null)
.<other operations...>
Run Code Online (Sandbox Code Playgroud)

对于更实用的样式,可以快速编写一个小辅助方法:

public static <T> boolean nonNull(T entity) {
    return entity != null;
}
Run Code Online (Sandbox Code Playgroud)

这样您就可以使用方法引用:

.stream()
.<other operations...>
.filter(Elements::nonNull)
.<other operations...>
Run Code Online (Sandbox Code Playgroud)

我找不到这样的jdk方法,即使我怀疑他们已经包含了一个.这里有不同的方法吗?或者他们是否因为某种原因而忽略了这一点?

Mat*_*zyk 30

您可以使用Java8 SDK中的Objects :: nonNull:

.stream()
.<other operations...>
.filter(Objects::nonNull)
.<other operations...>
Run Code Online (Sandbox Code Playgroud)