使用选项重写 if else null 检查
rewrite if else null check using optionals
有没有一种方法可以使用 Optional 和 lambda 以更简洁明了的方式重写它?
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(t)
.map(AvgBuySellPriceTerm::getIndicator)
.map(List::isEmpty)
.orElse(true);
但不确定这是否更具可读性。
下面应该使用 Optional::ofNullable
和经典的 map
、filter
和 isPresent
方法
private boolean pricingIndicator(AvgBuySellPriceTerm avgBuySellPriceTerm){
return Optional.ofNullable(avgBuySellPriceTerm)
.map(AvgBuySellPriceTerm::getIndicator)
.filter(ind -> !ind.isEmpty())
.isPresent();
}
同样,这里不使用 lambda,但要保持可读性。第一个if
语句可以省略,所以可以归结为:
private boolean pricingIndicator(AvgBuySellPriceTerm avgBuySellPriceTerm){
if(avgBuySellPriceTerm != null && avgBuySellPriceTerm.getIndicator()!= null && !avgBuySellPriceTerm.getIndicator().isEmpty()){
return true;
}
return false;
}
有没有一种方法可以使用 Optional 和 lambda 以更简洁明了的方式重写它?
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(t)
.map(AvgBuySellPriceTerm::getIndicator)
.map(List::isEmpty)
.orElse(true);
但不确定这是否更具可读性。
下面应该使用 Optional::ofNullable
和经典的 map
、filter
和 isPresent
方法
private boolean pricingIndicator(AvgBuySellPriceTerm avgBuySellPriceTerm){
return Optional.ofNullable(avgBuySellPriceTerm)
.map(AvgBuySellPriceTerm::getIndicator)
.filter(ind -> !ind.isEmpty())
.isPresent();
}
同样,这里不使用 lambda,但要保持可读性。第一个if
语句可以省略,所以可以归结为:
private boolean pricingIndicator(AvgBuySellPriceTerm avgBuySellPriceTerm){
if(avgBuySellPriceTerm != null && avgBuySellPriceTerm.getIndicator()!= null && !avgBuySellPriceTerm.getIndicator().isEmpty()){
return true;
}
return false;
}