Why does there seem to be no map()
/flatMap()
methods on OptionalInt or other primitive optional flavors?
The stream()
map operations allow conversion between objects and primitives. But why does Optional not exploit this?
OptionalInt profileId = OptionalInt.of(124); Optional<Profile> profile = profileId.map(i -> getProfile(i)); //no such valid map() method!
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. Where R is the element type of the new stream.
OptionalInt help us to create an object which may or may not contain a int value. The getAsInt() method returns value If a value is present in OptionalInt object, otherwise throws NoSuchElementException.
The flatMap() method of optionals allows you to transform the optional if it has a value, or do nothing if it is empty. This makes for shorter and more expressive code than doing a regular unwrap, and doesn't require you to change your data type.
Primitive optionals haven't map, flatMap and filter methods by design.
Moreover, according to Java8 in Action p.305 you shouldn't use them. The justification of use primitive on streams are the performance reasons. In case of huge number of elements, boxing/unboxing overhead is significant. But this is senselessly since there is only one element in Optional.
Besides, consider example:
public class Foo { public Optional<Integer> someMethod() { return Optional.of(42); } }
And usage as method reference:
.stream() .map(Foo::someMethod)
If you change return type of someMethod to OptionalInt:
public OptionalInt someMethod() { return OptionalInt.of(42); }
You cannot use it as method reference and code will not compile on:
.map(Foo::someMethod)
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