Can I not map/flatMap an OptionalInt?

2019-04-03 06:54发布

问题:

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!

回答1:

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)


回答2:

It seems in Java 9 OptionalInt will have a stream method that gives you an IntStream with either 0 or 1 element in it. On this stream you can of course use map(), flatMap() or filter(), etc.

For Java 8 I have nothing to add to user2138356’s answer.