30

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 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)

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

4

2 回答 2

23

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

于 2015-06-25T19:22:44.647 回答
-1

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

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

于 2015-06-26T02:42:39.897 回答