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

32k views Asked by At

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?

3

There are 3 answers

0
Brian Goetz On BEST ANSWER

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
Arun Pratap Singh On

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

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

0
Mohammed Yaseen M On

use filter before map.

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

filter(Objects::nonNull) try this instead .