假设我有:
public void func(){
Optional<Integer> firstRequiredOptional = ...
Optional<Integer> secondRequiredOptional = ...
if(firstRequiredOptional.isPresent() && secondRequiredOptional.isPresent()){
// do something with values of BOTH optionals
}
// Do nothing
}
[如果同时存在两个选件,则此功能将仅执行if
。
[我试图考虑一种更简洁的方式(也许是函数ifPresent
类型)编写此方法,或者在可能的情况下将两个int都转换为Optional<Integer, Integer>
,并且可能的话)
写这个的更干净的方法是什么?
if
语句已经比其他方法干净。替代1
ifPresent
,例如:firstRequiredOptional.ifPresent(first ->
secondRequiredOptional.ifPresent(second -> something(first, second)));
替代2如果您不想消耗(不是不可能的)值,请使用
allMatch
和Stream
,例如:
if (Stream.of(firstRequiredOptional, secondRequiredOptional) .allMatch(Optional::isPresent)) { something(); // or something(firstRequiredOptional.get(), secondRequiredOptional.get()); }
@ Naman指出,ifPresent
解决方案看起来像:
firstRequiredOptional.ifPresent(firstValue ->
secondRequiredOptional.ifPresent(secondValue -> {
// do something with firstValue, secondValue.
}));
这意味着您不必同时在两个可选项上同时调用.isPresent()
和.get()
。没有
Optional<FirstType, SecondType>
,但是如果这两个必需值的组合具有某种含义,则可能需要在一个类中体现出来。
Optional<FullName> fullNameOptional = firstNameOptional.flatMap(firstName -> secondNameOptional.map(secondName -> new FullName(firstName, secondName)); fullNameOptional.ifPresent(fullName -> { // do something with fullName. });
这具有为您提供一个可以使用的可选值,传递给辅助方法等的优点,并且它遵循Command-Query Separation模式,在调试和将代码分解成多个部分时,它通常具有优势。简单的单元测试。但这并不是说“干净”,例如,您使用的代码更少。如果您喜欢映射到单个
Optional
的想法,但不想为此创建类型,则可以创建通用的Tuple类(或使用几种流行的Tuple库之一)。] >也许是两个可选的通用方法:
import java.util.Optional; import java.util.function.BiConsumer; public class OptionalUtils { public static <T> void ifPresent(Optional<T> optional1, Optional<T> optional2, BiConsumer<T, T> consumer) { if (optional1.isPresent() && optional2.isPresent()) { consumer.accept(optional1.get(), optional2.get()); } } public static void main(String[] args) { Optional<Integer> test1 = Optional.of(1); Optional<Integer> test2 = Optional.of(2); ifPresent(test1, test2, (a, b) -> { System.out.println(" a + b =" + (a + b)); }); } }
不确定是否更清洁,但我的直观解决方案是提供一个容器并使用ofNullable
。这可能与以下内容类似:
public class DualOptional<T, K> { Optional<T> opt1 = Optional.empty(); Optional<K> opt2 = Optional.empty(); DualOptional( T t, K k ) { opt1 = Optional.ofNullable( t ); opt2 = Optional.ofNullable( k ); } public boolean isPresent() { return opt1.isPresent() && opt2.isPresent(); } }
当然可以扩展为包括吸气剂和其他所需的功能。
ofNullable
。ofNullable
。