Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using ifPresent with orElseThrow

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.

like image 636
Brett Sutton Avatar asked Dec 01 '22 09:12

Brett Sutton


2 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");});
like image 142
Naman Avatar answered Dec 04 '22 00:12

Naman


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"));
like image 29
daniu Avatar answered Dec 04 '22 01:12

daniu