How to convert an Optional to an OptionalInt?

前端 未结 5 900
醉梦人生
醉梦人生 2020-12-03 21:50

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

5条回答
  •  一个人的身影
    2020-12-03 22:23

    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.

提交回复
热议问题