Java 8 optional: ifPresent return object orElseThrow exception

前端 未结 4 1446
花落未央
花落未央 2020-12-03 09:17

I\'m trying to make something like this:

 private String getStringIfObjectIsPresent(Optional object){
        object.ifPresent(() ->{
               


        
      
      
      
4条回答
  •  独厮守ぢ
    2020-12-03 10:21

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

    Like this:

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

    提交回复
    热议问题