Java 8可选:ifPresent返回对象orElseThrow异常

Ric*_*rdK 28 java lambda optional

我想做这样的事情:

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

这不起作用,因为ifPresent将Consumer功能接口作为参数,其具有void accept(T t).它不能返回任何值.还有其他办法吗?

Rol*_*and 35

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

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

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;
}
Run Code Online (Sandbox Code Playgroud)

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


iam*_*ddy 13

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

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;
}
Run Code Online (Sandbox Code Playgroud)

或一个班轮

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


mar*_*ran 9

请改用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);
}
Run Code Online (Sandbox Code Playgroud)


Vla*_*nin 8

这里有两个选择:

替换ifPresentmap和使用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);
}
Run Code Online (Sandbox Code Playgroud)

用途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();
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 请注意,第二个选项不是推荐的使用Optional的方式 (2认同)
  • `map` 不是为了这种用途而设计的。它总是有一个返回类型,所以最好执行“return someOptional.orElseThrow(() -&gt; ...);”——不清楚 OP 是否打算返回某些内容。 (2认同)