Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 598
Brian Ecker Avatar asked Jun 25 '15 19:06

Brian Ecker


People also ask

What does the map () function do why you use it in Java?

The map() function is a method in the Stream class that represents a functional programming concept. In simple words, the map() is used to transform one object into other by applying a function. That's why the Stream. map(Function mapper) takes a function as an argument.

What is difference between map and filter in Java Stream?

Filter takes a predicate as an argument so basically you are validating your input/collection against a condition, whereas a map allows you to define or use a existing function on the stream eg you can apply String.

What is the purpose of map method of stream in Java 8 iterate each element of the stream?

Java 8 Stream map() function Example with Explanation Map is a function defined in java. util. stream. Streams class, which is used to transform each element of the stream by applying a function to each element.

Can we use stream with map in Java?

Converting only the Value of the Map<Key, Value> into Stream: This can be done with the help of Map. values() method which returns a Set view of the values contained in this map. In Java 8, this returned set can be easily converted into a Stream of key-value pairs using Set. stream() method.


1 Answers

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.

like image 188
Brian Goetz Avatar answered Oct 21 '22 04:10

Brian Goetz