Get value from one Optional or another

前端 未结 4 1053
轮回少年
轮回少年 2020-11-28 06:55

I have two java.util.Optional instances and I want to get an Optional that either:

  • Has the value of the first Optional, if it has a v
4条回答
  •  死守一世寂寞
    2020-11-28 07:33

    I had a few encounters with a problem that might've been solved with JDK 9 Optional::or and couldn't because we use JDK 8. Finally I added a util class with this method:

    @SafeVarargs
    public static  Optional firstPresent(final Supplier>... optionals) {
        return Stream.of(optionals)
                .map(Supplier::get)
                .filter(Optional::isPresent)
                .findFirst()
                .orElse(Optional.empty());
    }
    

    Now you can supply any number of optionals to this method and they'll be lazily evaluated like so:

        final Optional username = OptionalUtil.firstPresent(
                () -> findNameInUserData(user.getBasicData()),
                () -> findNameInUserAddress(user.getAddress()),
                () -> findDefaultUsername());
    

    Now, findNameInUserAddress will only be called if findNameInUserData returns empty. findDefaultUsername will only be called if both findNameInUserData and findNameInUserAddress return empty etc.

提交回复
热议问题