Using multiple map functions vs. a block statement in a map in a java stream(在 java 流的映射中使用多个映射函数与块语句)
问题描述
假设我有以下代码
data.stream()
.map(x -> {
Object a = maybeReturnsNull(x);
return a == null ? defaultValue : a;
})
我有一些可能返回 null
的函数,我将它应用到流的一个元素.然后,我想确保将任何 null
结果更改为某个默认值.与使用前面定义辅助变量 a
并在 lambda 表达式中使用代码块的示例相比,使用以下示例中的两个映射之间是否有任何显着差异?
I have some function that might be returning null
, and I'm applying it to an element of the stream. I then want to make sure that any null
results get changed to some default value instead. Is there any significant difference between using two maps as in the following example, as compared to using the previous example that defines a helper variable a
and uses a code block in the lambda expression?
data.stream()
.map(x -> maybeReturnsNull(x))
.map(x -> x == null ? defaultValue : x)
是否有关于在何处避免使用带有 lambda 函数的块语句的标准?
Is there a standard on where or not to avoid using block statements with lambda functions?
推荐答案
两者都可以.选择对您来说更具可读性的一个.如果计算自然分解,就像这个一样,那么多张地图可能更具可读性.有些计算不会自然分解,在这种情况下,你会被困在前者.在这两种情况下,您都不应该担心其中一种性能明显优于另一种;这在很大程度上是不考虑的.
Either is fine. Pick the one that seems more readable to you. If the calculation naturally decomposes, as this one does, then the multiple maps is probably more readable. Some calculations won't naturally decompose, in which case you're stuck at the former. In neither case should you be worrying that one is significantly more performant than the other; that's largely a non-consideration.
这篇关于在 java 流的映射中使用多个映射函数与块语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 java 流的映射中使用多个映射函数与块语句
基础教程推荐
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01
- 降序排序:Java Map 2022-01-01
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01
- 如何使用 Java 创建 X509 证书? 2022-01-01