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

Categories

0 votes
118 views
in Technique[技术] by (71.8m points)

java - How to convert an Optional to an OptionalInt?

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

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

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...