Brett Sutton
Brett Sutton

Reputation: 4554

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.

Upvotes: 5

Views: 9454

Answers (3)

Sivaram Rasathurai
Sivaram Rasathurai

Reputation: 6343

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

Upvotes: 3

Naman
Naman

Reputation: 31888

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");});

Upvotes: 15

daniu
daniu

Reputation: 15008

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

Upvotes: 9

Related Questions