2017-04-19 65 views
2

的isPresent代码,这是条件语句,它可以使用ifPresent来代替它?:如何优化的Java

if (mo.findParameterValueByPath("primaryCRLDP").isPresent() 
    && mo.findParameterValueByPath("secondaryCRLDP").isPresent() 
&& mo.findParameterValueByPath("primaryCRLDP").get().equals(mo.findParameterValueByPath("secondaryCRLDP").get())) { 
return true; 
} 
+0

也许这样的代码是为什么给我们任选项的人告诉我们主要用它们作为方法参数的原因之一,而不是返回类型 – GhostCat

+0

@GhostCat看到编辑失败;) –

+1

是的,手机不是这种活动的理想设备... – GhostCat

回答

2

Optional<T>#ifPresent需要Consumer<? super T>作为参数,并没有返回,所以你不会能够使用它来“优化”上面的代码。老实说,有没有什么可以再说的变量存储每个Optional<T>做,你不需要调用findParameterValueByPath两次,每次:

Optional<T> o1 = mo.findParameterValueByPath("primaryCRLDP"); 
Optional<T> o2 = mo.findParameterValueByPath("secondaryCRLDP"); 

return o1.isPresent() && o2.isPresent() && o1.get().equals(o2.get()); 

你并没有说明具体的泛型类型的Optional<T>用途,所以我在上面的例子中将其留为通用的。

+1

不错。简短,精确的点! – GhostCat

+0

@GhostCat谢谢!我会说没有更多的事情可以做,但我可能是错的。 –

+0

实际上,自[Optionals比较其内容](https://docs.oracle.com/javase/8/docs/api/java/util/Optional.html#equals-java.lang.Object-)以来,return语句可以是'return o1.equals(o2);'。 – VGR