在java流中使用多个映射函数与映射中的块语句 [英] Using multiple map functions vs. a block statement in a map in a java stream

查看:245
本文介绍了在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流中使用多个映射函数与映射中的块语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆