Java 8 optional: ifPresent return object orElseThrow exception

前端 未结 4 1447
花落未央
花落未央 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:05

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

    private String getStringIfObjectIsPresent(Optional 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) {
       return your-map-function(object.orElseThrow(MyCustomException::new));
    }
    
        

    提交回复
    热议问题