Java 8可选:ifPresent返回对象或ElseThrow异常
我正在尝试做这样的事情:
 private String getStringIfObjectIsPresent(Optional<Object> object){        object.ifPresent(() ->{
            String result = "result";
            //some logic with result and return it
            return result;
        }).orElseThrow(MyCustomException::new);
    }
这将不起作用,因为ifPresent将消费者功能接口作为参数,其具有无效的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等等,因为我发现它更具可读性(显然是主观决定;-)。
以上是 Java 8可选:ifPresent返回对象或ElseThrow异常 的全部内容, 来源链接: utcz.com/qa/435609.html



