35

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?

Tagir Valeev
  • 97,161
  • 19
  • 222
  • 334
Brian Ecker
  • 2,017
  • 1
  • 21
  • 30
  • 2
    or `.map(this::maybeReturnsNull).map(Optional::ofNullable).map(o -> o.orElse(defaultValue))` – assylias Jun 26 '15 at 07:22
  • 4
    @assylias: even if it doesn’t make a difference in performance, I think a single `.map(x -> Optional.ofNullable(maybeReturnsNull(x)).orElse(defaultValue))` should be preferred over three mapping steps here. But well, it’s still a matter of taste… – Holger Jun 26 '15 at 09:16

3 Answers3

28

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.

Brian Goetz
  • 90,105
  • 23
  • 150
  • 161
0

use filter before map.

data.stream().filter(Objects::nonNull).
    .map(x -> x*x)

filter(Objects::nonNull) try this instead .
-4

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

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

Arun Pratap Singh
  • 3,428
  • 30
  • 23