Reputation: 4554
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
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
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
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