Java 8 Optional<T> get

420 views Asked by At

Java 8 Optional method get throws an exception when does not exists the element. Why does throws exception instead of return null or an Optional empty?

2

There are 2 answers

0
Tagir Valeev On BEST ANSWER

Use .orElse(null) if you want null. The idea of Optional is to force you to explicitly handle the absence of the value.

0
Manasi On

You can you Optional.orElse(null) if you need null or the value

Optional optional  = Optional.empty();
System.out.println(optional.orElse(null));

If there is some operation or action you want to perform you an use OptionalifPresent(Consumer operationToPerform)

optional.ifPresent(o->{ // operation to perform
System.out.println(o); });