I have an Optional that I want to \"convert\" to an OptionalInt, but there doesn\'t seem to be a simple way to do this.
Here\'s what I want
No, there's no way to do it in more elegant way using standard Java API. And as far as I know it's not planned to add such methods in JDK-9. I asked Paul Sandoz about adding mapToInt, etc., here's his answer:
Me:
Isn't it a good idea to provide also a way to transfer between
Optionaltypes likemapToInt,mapToObj, etc., like it's done in Stream API?
Paul:
I don’t wanna go there, my response is transform
Optional*into a*Stream. An argument for addingmapOrElseGet(notice that the primitive variants returnU) is that other functionality can be composed from it.
So you will likely to have in Java-9:
return Optional.of(someString).filter(s -> s.matches("\\d+"))
.mapOrElseGet(s -> OptionalInt.of(Integer.parseInt(s)), OptionalInt::empty);
But nothing more.
That's because JDK authors insist that the Optional class and its primitive friends (especially primitive friends) should not be widely used, it's just a convenient way to perform a limited set of operations on the return value of methods which may return "the absence of the value". Also primitive optionals are designed for performance improvement, but actually it's much less significant than with streams, so using Optional is also fine. With Valhalla project (hopefully to arrive in Java-10) you will be able to use Optional and OptionalInt will become unnecessary.
In your particular case the better way to do it is using ternary operator:
return someString != null && someString.matches("\\d+") ?
OptionalInt.of(Integer.parseInt(someString)) : OptionalInt.empty();
I assume that you want to return the OptionalInt from the method. Otherwise it's even more questionable why you would need it.