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?
Java 8 Optional<T> get
390 views Asked by Homilzio Trovoada Santos At
2
There are 2 answers
0
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); });
Use
.orElse(null)
if you want null. The idea ofOptional
is to force you to explicitly handle the absence of the value.