The advantage of OptionalInt
over Optional<Integer>
is that you can avoid the boxing operation if the source is a primitive int
value.
This does not apply if the source is already an Integer
. In that case, if your next operation requires an int
, an unboxing operation will always occur, either at the time you construct an OptionalInt
or when chaining the next operation with an Optional<Integer>
. So using an OptionalInt
offers no advantage then.
Keep in mind that it is not the intention of these classes to be used as parameter types, so there should be no code expecting an OptionalInt
as input. To cite a recent statement from Brian Goetz:
Our intention was to provide a limited mechanism for library method return types where there needed to be a clear way to represent "no result", and using null
for such was overwhelmingly likely to cause errors.
(emphasis by me)
Btw., you can convert an Optional<Integer>
to an OptionalInt
without the conditional operator using the usual operations of Optional
:
Integer boxed=null;
OptionalInt optInt=Optional.ofNullable(boxed)
.map(OptionalInt::of).orElseGet(OptionalInt::empty);
Starting with Java 9, you can also use
OptionalInt optInt=Stream.ofNullable(boxed).mapToInt(Integer::intValue).findAny();
But, as said, it shouldn’t be necessary as normally you simply specify the follow-up operation which will consume either int
or Integer
, if present. And this works with both, Optional
and OptionalInt
.