有没有办法以更简洁和清晰的方式使用可选和lambdas重写?
private boolean pricingIndicator(AvgBuySellPriceTerm avgBuySellPriceTerm){
if(avgBuySellPriceTerm == null){
return false;
}else{
if(avgBuySellPriceTerm.getIndicator()!= null && ! avgBuySellPriceTerm.getIndicator().isEmpty()){
return true;
}else{
return false;
}
}
}
这是Optional
的建议:
private boolean pricingIndicator(AvgBuySellPriceTerm avgBuySellPriceTerm){
return Optional.ofNullable(avgBuySellPriceTerm)
.map(AvgBuySellPriceTerm::getIndicator)
.map(i -> !i.isEmpty()) // return true if getIndicator
// is not empty
.orElse(false);
}
使用Optional::ofNullable
和经典map
,filter
和isPresent
方法
private boolean pricingIndicator(AvgBuySellPriceTerm avgBuySellPriceTerm){
return Optional.ofNullable(avgBuySellPriceTerm)
.map(AvgBuySellPriceTerm::getIndicator)
.filter(ind -> !ind.isEmpty())
.isPresent();
}
!Optional.ofNullable(t)
.map(AvgBuySellPriceTerm::getIndicator)
.map(List::isEmpty)
.orElse(true);
不确定这是更可读的。
再次,在这里不使用lambdas,而是保持它可读。可以省略第一个if
语句,因此可以归结为:
private boolean pricingIndicator(AvgBuySellPriceTerm avgBuySellPriceTerm){
if(avgBuySellPriceTerm != null && avgBuySellPriceTerm.getIndicator()!= null && !avgBuySellPriceTerm.getIndicator().isEmpty()){
return true;
}
return false;
}