Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I not map/flatMap an OptionalInt?

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! 
like image 333
tmn Avatar asked Mar 17 '15 16:03

tmn


People also ask

What is the difference between MAP and flatMap?

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.

What is OptionalInt?

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.

What is flatMap in optional?

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.


1 Answers

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) 
like image 153
fasth Avatar answered Sep 19 '22 13:09

fasth