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?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With