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.
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"));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With