Java 8 optional: ifPresent return object orElseThrow exception

前端 未结 4 1437
花落未央
花落未央 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> 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> object) {
        if (object.isPresent()) {
            String result = "result";
            //some logic with result and return it
            return result;
        } else {
            throw new MyCustomException();
        }
    }
    
    0 讨论(0)
  • 2020-12-03 10:05

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

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

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

    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 ;-)).

    0 讨论(0)
  • 2020-12-03 10:05

    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));
    }
    
    0 讨论(0)
  • 2020-12-03 10:21

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

    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);
    }
    
    0 讨论(0)
提交回复
热议问题