How to convert an Optional to an OptionalInt?

前端 未结 5 872
醉梦人生
醉梦人生 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:15

    If you have any object and not just a String, you can temporarily go through a Stream:

    public static  OptionalInt toOptionalInt(Optional optional, ToIntFunction 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 func) {
      if (optional.isPresent()) {
        return OptionalInt.of(func.applyAsInt(optional.get()));
      } else {
        return OptionalInt.empty();
      }
    }
    

提交回复
热议问题