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
If you have any object and not just a String
, you can temporarily go through a Stream
:
public static OptionalInt toOptionalInt(Optional optional, ToIntFunction super T> func) {
return optional.map(Stream::of).orElseGet(Stream::empty)
.mapToInt(func)
.findFirst();
}
This solution has the advantage to be a one-liner, meaning you can copy/paste the content of the method and just change func
to whatever you want. The disadvantage is going through a Stream to achieve what you want. But if you want a generic one-liner, this is it.
If you want a utility method, you probably prefer to use the following:
public static OptionalInt toOptionalInt(Optional optional, ToIntFunction super T> func) {
if (optional.isPresent()) {
return OptionalInt.of(func.applyAsInt(optional.get()));
} else {
return OptionalInt.empty();
}
}