Filter Null items in Stream(过滤 Stream 中的 Null 项)
问题描述
When using a Java Stream, sometimes null values can occur after mapping. Currently when these values need to be omitted, I use:
.stream()
.<other operations...>
.filter(element -> element != null)
.<other operations...>
For a more functional style a tiny helper method is quickly written:
public static <T> boolean nonNull(T entity) {
return entity != null;
}
So that you can use a method reference instead:
.stream()
.<other operations...>
.filter(Elements::nonNull)
.<other operations...>
I could not find such a jdk method, even though I would suspect they have included one. Is there a different approach here? Or did they omit this for a reason?
You can use Objects::nonNull from the Java8 SDK:
.stream()
.<other operations...>
.filter(Objects::nonNull)
.<other operations...>
这篇关于过滤 Stream 中的 Null 项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:过滤 Stream 中的 Null 项
基础教程推荐
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01
- 如何使用 Java 创建 X509 证书? 2022-01-01
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- 降序排序:Java Map 2022-01-01
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01