如果使用选项为单位,则重写是否为null



有没有办法以更简洁和清晰的方式使用可选和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和经典mapfilterisPresent方法

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;
}

最新更新