繁体   English   中英

Java 8 可选:ifPresent 返回 object orElseThrow exception

[英]Java 8 optional: ifPresent return object orElseThrow exception

我正在尝试做这样的事情:

 private String getStringIfObjectIsPresent(Optional<Object> object){
        object.ifPresent(() ->{
            String result = "result";
            //some logic with result and return it
            return result;
        }).orElseThrow(MyCustomException::new);
    }

这是行不通的,因为ifPresent以Consumer函数接口为参数,它有void accept(T t)。 它不能返回任何值。 还有其他方法吗?

实际上你在搜索的是: Optional.map 您的代码将如下所示:

object.map(o -> "result" /* or your function */)
      .orElseThrow(MyCustomException::new);

如果可以,我宁愿省略传递Optional 最后,使用Optional可以获得任何结果。 一个稍微其他的变体:

public String getString(Object yourObject) {
  if (Objects.isNull(yourObject)) { // or use requireNonNull instead if NullPointerException suffices
     throw new MyCustomException();
  }
  String result = ...
  // your string mapping function
  return result;
}

如果你因为另一个电话已经有了Optional -object,我仍然会建议你使用map -method,而不是isPresent等,原因只有一个,我发现它更具可读性(显然是一个主观决定;-) )。

在确定值可用后,我更喜欢映射

private String getStringIfObjectIsPresent(Optional<Object> object) {
   Object ob = object.orElseThrow(MyCustomException::new);
    // do your mapping with ob
   String result = your-map-function(ob);
  return result;
}

或一个班轮

private String getStringIfObjectIsPresent(Optional<Object> object) {
   return your-map-function(object.orElseThrow(MyCustomException::new));
}

请改用map -function。 它会转换可选内部的值。

像这样:

private String getStringIfObjectIsPresent(Optional<Object> object) {
    return object.map(() -> {
        String result = "result";
        //some logic with result and return it
        return result;
    }).orElseThrow(MyCustomException::new);
}

这里有两个选择:

ifPresent替换为map并使用Function而不是Consumer

private String getStringIfObjectIsPresent(Optional<Object> object) {
    return object
            .map(obj -> {
                String result = "result";
                //some logic with result and return it
                return result;
            })
            .orElseThrow(MyCustomException::new);
}

使用isPresent

private String getStringIfObjectIsPresent(Optional<Object> object) {
    if (object.isPresent()) {
        String result = "result";
        //some logic with result and return it
        return result;
    } else {
        throw new MyCustomException();
    }
}

你举的例子不是一个很好的例子。 可选不应该作为参数发送到另一个 function。好的做法是始终将非空参数发送到 function。这样我们就知道输入不会是 null。这可以减少我们的代码不确定性。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM