java多选项,选择最佳?
我有一个可以包含多个可选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);
}
有没有比我现有的方法更好的方法?我很想通过执行香草isPresent()检查来避免嵌套
# 1 楼答案
在国际海事组织看来,这种方法更具可读性和可扩展性。我们可以使用^{} 方法将那些
Optional
包装成一个流,然后找到第一个存在一个退步是我们需要
@SafeVarargs
来抑制警告,这是根据Is it possible to solve the “A generic array of T is created for a varargs parameter” compiler warning?无法避免的