多个选项,选择最佳?

csbfibhn  于 2021-07-06  发布在  Java
关注(0)|答案(1)|浏览(196)

这个问题在这里已经有答案了

Java8中的链接选项(7个答案)
上个月关门了。
我有一个可以包含多个可选id的类,该类将选择第一个可用id并将其返回给调用者。像下面这样。

Optional<Phone> homePhone;
Optional<Phone> mobilePhone;
Optional<Phone> emergencyPhone;

Phone getBestPhone() {
  return homePhone.map(p -> p)
           .orElse(mobilePhone.map(p -> p)
             .orElse(emergencyPhone.map(p -> p)
               .orElseThrow(() -> new IllegalArgument("No valid phone")))));
}

我想使用可选的方法,如map和orelse,但在这种情况下,它会导致太多的嵌套。可能需要另外两个伪代码选项。

Phone getBestPhone() {
  homePhone.ifPresent(p -> { return p; });
  mobilePhone.ifPresent(p -> { return p; });
  emergencyPhone.ifPresent(p -> { return p; });
  throw new IllegalArgument("...");
}
Phone getBestPhone() {
  return FirstPresent(homePhone, mobilePhone, emergencyPhone);
}

有没有比我现有的方法更好的方法?我很想通过执行vanilla ispresent()检查来避免嵌套。

cedebl8k

cedebl8k1#

国际海事组织, firstPersent 这种方法似乎更具可读性和可扩展性。我们可以利用 Stream#of(T...) 方法来 Package 这些 Optional 到一条小溪,然后找到第一个礼物。

import java.util.Optional;
import java.util.stream.Stream;

public class GetFirstPresent {
    public static void main(String[] args) {
        Optional<Phone> homePhone = Optional.empty();
        Optional<Phone> mobilePhone = Optional.empty();
        Optional<Phone> emergencyPhone = Optional.of(new Phone("e123"));
        Phone phone = firstPresent(homePhone, mobilePhone, emergencyPhone);
        System.out.println(phone.id);
        try {
            firstPresent(homePhone, mobilePhone);
        } catch (IllegalArgumentException e) {
            System.out.println(e);
        }
    }

    @SafeVarargs
    private static Phone firstPresent(Optional<Phone>... phones) {
        return Stream.of(phones).filter(Optional::isPresent)
                .findFirst().map(Optional::get).orElseThrow(() -> {
                    return new IllegalArgumentException("No phone present");
                });
    }

    private static class Phone {
        public Phone(String id) {
            super();
            this.id = id;
        }

        private String id;
    }
}

我们需要一个退路 @SafeVarargs 为了抑制警告,这是无法避免的,根据是否有可能解决“为varargs参数创建t的泛型数组”编译器警告?

相关问题