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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41485751/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 23:25:10  来源:igfitidea点击:

Java 8 optional: ifPresent return object orElseThrow exception

javalambdaoptional

提问by RichardK

I'm trying to make something like this:

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

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

This won't work, because ifPresent takes Consumer functional interface as parameter, which has void accept(T t). It cannot return any value. Is there any other way to do it ?

这是行不通的,因为 ifPresent 将 Consumer 功能接口作为参数,该接口具有 void accept(T t)。它不能返回任何值。有没有其他方法可以做到?

采纳答案by Roland

Actually what you are searching is: Optional.map. Your code would then look like:

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

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

I would rather omit passing the Optionalif you can. In the end you gain nothing using an Optionalhere. A slightly other variant:

Optional如果可以的话,我宁愿省略传递。最后,使用Optionalhere 将一无所获。一个稍微不同的变体:

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

If you already have the Optional-object due to another call, I would still recommend you to use the map-method, instead of isPresent, etc. for the single reason, that I find it more readable (clearly a subjective decision ;-)).

如果Optional由于另一个调用您已经有了-object,我仍然建议您使用map-method,而不是isPresent等,原因只有一个,我觉得它更具可读性(显然是主观决定;-))。

回答by marstran

Use the map-function instead. It transforms the value inside the optional.

改用map- 函数。它转换可选中的值。

Like this:

像这样:

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

回答by Vlad Bochenin

Two options here:

这里有两个选项:

Replace ifPresentwith mapand use Functioninstead of Consumer

替换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);
}

Use isPresent:

使用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();
    }
}

回答by iamiddy

I'd prefer mapping after making sure the value is available

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

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

or one liner

或一个班轮

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