Java 8 optional: ifPresent return object orElseThrow exception

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

I\'m trying to make something like this:

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


        
      
      
      
4条回答
  •  醉梦人生
    2020-12-03 09:56

    Two options here:

    Replace ifPresent with map and use Function instead of Consumer

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

    Use isPresent:

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

    提交回复
    热议问题