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 to do (contrived example):
public OptionalInt getInt() {
return Optional.ofNullable(someString).filter(s -> s.matches("\d+")).mapToInt(Integer::parseInt);
}
However, there's no mapToInt()
method for Optional
.
The best I could come up with is:
return Optional.ofNullable(someString)
.filter(s -> s.matches("\d+"))
.map(s -> OptionalInt.of(Integer.parseInt(s)))
.orElse(OptionalInt.empty());
but that seems inelegant.
Am I missing something from the JDK that can make the conversion more elegant?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…