The advantage of OptionalInt over Optional<Integer> is that you can avoid the box operation if the source is a primitive int value.
This does not apply if the source is already an Integer . In this case, if an int is required for the next operation, the unboxing operation will always be performed either upon creation of OptionalInt , or at the next next connection using Optional<Integer> . Therefore, using OptionalInt does not offer benefits.
Keep in mind that these classes are not intended to be used as parameter types, so there should be no code waiting for OptionalInt input. To quote a recent expression by Brian Goetz :
Our intention was to provide a limited mechanism for return types of method methods , where there should be a clear way to represent "no result", and using null for such purposes is in the vast majority of errors.
(highlighted by me)
Btw., You can convert Optional<Integer> to OptionalInt without a conditional statement using the usual Optional operations:
Integer boxed=null; OptionalInt optInt=Optional.ofNullable(boxed) .map(OptionalInt::of).orElseGet(OptionalInt::empty);
But, as said, it should not be necessary, since usually you just specify the subsequent operation, which will consume either int or Integer , if present. And this works with both, Optional and OptionalInt .
source share