How to convert an Optional to an OptionalInt?
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
Optional
types 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<Integer>
is also fine. With Valhalla project (hopefully to arrive in Java-10) you will be able to use Optional<int>
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.
While the code isn't more readable than an ordinary conditional expression, there is a simple solution:
public OptionalInt getInt() {
return Stream.of(someString).filter(s -> s != null && s.matches("\\d+"))
.mapToInt(Integer::parseInt).findAny();
}
With Java 9, you could use
public OptionalInt getInt() {
return Stream.ofNullable(someString).filter(s -> s.matches("\\d+"))
.mapToInt(Integer::parseInt).findAny();
}
As said, neither is more readable than an ordinary conditional expression, but I think, it still looks better than using mapOrElseGet
(and the first variant doesn't need Java 9.