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

后端 未结 2 1102
囚心锁ツ
囚心锁ツ 2020-12-09 16:28

Say I have the following code

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


        
相关标签:
2条回答
  • 2020-12-09 17:06

    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.

    0 讨论(0)
  • 2020-12-09 17:15

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

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

    0 讨论(0)
提交回复
热议问题