The Optional.or
method was added in Java 9. This is the method signature
public Optional<T> or(Supplier<? extends Optional<? extends T>> supplier)
Why is the type parameter of the Supplier
taking ? extends Optional
rather than just Optional
, since Optional
is a final class?
The same is true for the Optional.flatMap
method. This is a change from Java 8.
In Java 8, it was Function<? super T, Optional<U>> mapper
whereas it was changed to Function<? super T,? extends Optional<? extends U>>
in Java 9.
Both of the functions map() and flatMap are used for transformation and mapping operations. map() function produces one output for one input value, whereas flatMap() function produces an arbitrary no of values as output (ie zero or more than zero) for each input value.
Array.prototype.flatMap() The flatMap() method returns a new array formed by applying a given callback function to each element of the array, and then flattening the result by one level.
Does flatmap() method preserve the order of the streams? Yes, It does and map() also.
In Java 8 Streams, the flatMap() method applies operation as a mapper function and provides a stream of element values. It means that in each iteration of each element the map() method creates a separate new stream. By using the flattening mechanism, it merges all streams into a single resultant stream.
I found the reasoning behind this from Stuart Marks himself
http://mail.openjdk.java.net/pipermail/core-libs-dev/2016-October/044026.html
This has to do with nested generics (Optional
is nested within Function
). From the mail thread
Function<..., Optional<StringBuilder>>
is not a subtype of
Function<..., Optional<? extends CharSequence>>
To get around this, we have to add the outer wildcard as well, so that
Function<..., Optional<StringBuilder>>
is a subtype of
Function<..., ? extends Optional<? extends CharSequence>>
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