Can I not map/flatMap an OptionalInt?

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)

Leave a Comment

tech