Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
115 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...