Search code examples
javaoption-type

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.


Solution

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