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

时间:2015-06-25 19:06:47

标签: java java-8 java-stream map-function

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?

2 个答案:

答案 0 :(得分:13)

要么是好的。选择一个看起来更具可读性的那个。如果计算自然地分解,就像这样,那么多个映射可能更具可读性。有些计算不会自然地分解,在这种情况下你会被困在前者身上。在任何一种情况下,你都不应该担心一个人的表现要比另一个人高得多;这在很大程度上是不考虑的。

答案 1 :(得分:0)

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

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