如何避免使用Optional,get和Optional.isPresent

5f0d552i  于 2022-10-22  发布在  Java
关注(0)|答案(3)|浏览(167)
public ValueA map(ValueB valueB, Date date) {
    Optional<ValueC> valueCOpt = find(valueB);
    if (valueCOpt.isPresent()) {
        ValueC valueC = valueCOpt.get();
        // call many getters on valueC and do a lot of logic with it.
        return map(/*some parameters*/);
    }
    return null;
}

这看起来很难看。期权的优势在这里完全消失了。我读到,应该使用mapflatMap而不是get

valueC.getFieldA()

具有

valueCOpt.map(ValueC::getFieldA)

你知道这里的一些常见或最佳实践吗?

trnvg8h3

trnvg8h31#

您可以使用

public ValueA map(ValueB valueB, Date date) {
    return find(valueB)
        .map(valueC -> {
            // call many getters on valueC and do a lot of logic with it.
            return map(/*some parameters*/);
        })
        .orElse(null);
}

关键点是,Map函数仅在可选值不为空的情况下进行求值,否则,结果将保持为空可选值。如果可选项为空,orElse(null)将返回null

u5rb5r59

u5rb5r592#

你需要的是Map,然后是一个orElse(),或者如果你需要一个异常,则是orElseThrow()

ValueA valueA = valueCOpt.map(valueC -> mapToValue(valueC))
       .orElse(null);

当需要默认值时使用orElse(),在本例中为null

uajslkp6

uajslkp63#

给定行return map(/*some parameters*/);,您是否打算创建对map方法的递归调用?
假设您没有尝试递归方法调用。。。
为了澄清,我会重新修改您的方法,使其看起来更像:

public Optional<ValueA> process(ValueB valueB, Date date) {
    Optional<ValueC> valueCOpt = find(valueB);
    if (valueCOpt.isPresent()) {
        ValueC valueC = valueCOpt.get();
        // call many getters on valueC and do a lot of logic with it.
        return Optional.of(new ValueA(/*results of above logic as parameters*/));
    }
    return Optional.empty();
}

然后我将对其进行重构,以完全消除.isPresent.get方法对Optional的调用,并将其替换为.flatMap,如下所示:

public Optional<ValueA> process(ValueB valueB, Date date) {
    find(valueB)
        .flatMap(valueC -> {
            // call many getters on valueC and do a lot of logic with it.
            return Optional.of(new ValueA(/*results of above logic as parameters*/));
        });
}

如您所见,如果valueC存在,.flatMap方法可以从Optional<ValueC>中提取valueC,然后返回的值是手动 Package 的ValueA。当.flatMapOptional<ValueC>上被调用并且为空时,它会自动返回Optional<ValueA>.empty()
如果在处理valueC期间发现ValueA无法示例化,则必须返回Optional.empty(),如下所示:

public Optional<ValueA> process(ValueB valueB, Date date) {
    find(valueB)
        .flatMap(valueC -> {
            // call many getters on valueC and do a lot of logic with it.
          boolean isValueCProcessingSuccessful = false;
          return (isValueCProcessingSuccessful)
              ? Optional.of(new ValueA(/*results of above logic as parameters*/))
              : Optional.empty();
        });
}

相关问题