Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 optional: ifPresent return object orElseThrow exception

I'm trying to make 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 won't work, because ifPresent takes Consumer functional interface as parameter, which has void accept(T t). It cannot return any value. Is there any other way to do it ?

like image 958
RichardK Avatar asked Jan 05 '17 12:01

RichardK


People also ask

What does orElseThrow return?

The orElseThrow method will return the value present in the Optional object. If the value is not present, then the supplier function passed as an argument is executed and an exception created on the function is thrown.

How do you use orElseThrow in optional?

orElseThrow. Simply put, if the value is present, then isPresent() would return true, and calling get() will return this value. Otherwise, it throws NoSuchElementException.

How do you throw an exception if optional is empty?

Use the orElseThrow() method of Optional to get the contained value or throw an exception, if it hasn't been set. This is similar to calling get() , except that it allows for arbitrary exception types. The method takes a supplier that must return the exception to be thrown.

How do you return optional value?

To return the value of an optional, or a default value if the optional has no value, you can use orElse(other) . Note that I rewrote your code for finding the longest name: you can directly use max(comparator) with a comparator comparing the length of each String.


1 Answers

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

like image 115
Roland Avatar answered Oct 10 '22 10:10

Roland