using ifPresent with orElseThrow

Viewed 4799

So I must be missing something, I'm looking to execute a statement block if an Optional is present otherwise throw an exception.

Optional<X> oX;

oX.ifPresent(x -> System.out.println("hellow world") )
.orElseThrow(new RuntimeException("x is null");

if oX is not null then print hellow world. if oX is null then throw the runtime exception.

3 Answers

With Java-8, what you can do is use if...else as:

if(oX.ifPresent()) {
    System.out.println("hello world");  // ofcourse get the value and use it as well
} else { 
   throw new RuntimeException("x is null");
}

With Java-9 and above, you can use ifPresentOrElse

optional.ifPresentOrElse(s -> System.out.println("hello world"), 
        () -> {throw new RuntimeException("x is null");});

Just consume your element directly.

X x = oX.orElseThrow(new RuntimeException("x is null");
System.out.println(x);

Or

System.out.println(oX.orElseThrow(new RuntimeException("x is null"));

The accepted answer has an issue when the throwable is not implemented with the Supplier interface. To Avoid That, You can use the lambda expression as below.

X x = oX.orElseThrow(()-> new CustomException("x is null");
System.out.println(x);
Related