在 java 流中的映射中使用多个映射函数与块语句

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31058755/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 18:01:28  来源:igfitidea点击:

Using multiple map functions vs. a block statement in a map in a java stream

javajava-8java-streammap-function

提问by Brian Ecker

Say I have the following code

说我有以下代码

data.stream()
    .map(x -> {
        Object a = maybeReturnsNull(x);
        return a == null ? defaultValue : a;
    })

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 nullresults 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 aand uses a code block in the lambda expression?

我有一些可能会返回的函数,null我将它应用于流的一个元素。然后我想确保将任何null结果更改为某个默认值。与使用定义辅助变量a并在 lambda 表达式中使用代码块的前一个示例相比,使用以下示例中的两个映射之间是否存在显着差异?

data.stream()
    .map(x -> maybeReturnsNull(x))
    .map(x -> x == null ? defaultValue : x)

Is there a standard on where or not to avoid using block statements with lambda functions?

是否有关于在何处避免使用带有 lambda 函数的块语句的标准?

采纳答案by Brian Goetz

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.

哪个都好。选择一个对你来说更具可读性的。如果计算自然分解,就像这个一样,那么多个映射可能更具可读性。有些计算不会自然分解,在这种情况下,您会陷入前者。在这两种情况下,您都不应该担心一个的性能明显高于另一个;这在很大程度上是一种非考虑因素。

回答by Arun Pratap Singh

java has provided a dedicated API to handle with "null".

java 提供了一个专用的 API 来处理“null”。

https://docs.oracle.com/javase/8/docs/api/java/util/Optional.html

https://docs.oracle.com/javase/8/docs/api/java/util/Optional.html