Java 8 optional: ifPresent return object or ElseThrow exception

I am trying to do 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 will not work because ifPresent uses the consumer functional interface as a parameter that has void accept (T t). He cannot return any value. Is there any other way to do this?

+6
source share
4 answers

I would prefer matching, making sure this 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)); } 
+8
source

You are actually looking for: Optional.map . Then your code will look like this:

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

I would prefer to skip Optional , if possible. You end up with nothing using Optional here. A slightly different option:

 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 an Optional object due to another call, I still recommend that you use the map method rather than isPresent , etc. for one reason, that I find it more readable (obviously a subjective solution ;-)).

+11
source

Use the map function. It converts the value inside 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); } 
+4
source

Two options:

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(); } } 
+2
source

Source: https://habr.com/ru/post/1013794/


All Articles