I have recently been spending some time getting familiar with the Stream API, also introduced in Java 8, and a lot of the terminating methods of the Stream API returns an Optional<T>...
At first encounter with Optional<T>, my first thought was asking what real advantage does this offer? How is it different from checking if an object is null before calling its methods?
The Optional<T> has the isPresent() and get() methods which can be used to check if the enclosing object is null or not, and then retrieve it. Like so:
Optional<SomeType> someValue = someMethod(); if (someValue.isPresent()) { // check someValue.get().someOtherMethod(); // retrieve and call }
But exactly the same thing can be done with plain null checks with the code looking almost the same:
SomeType someValue = someMethod(); if (someValue != null) { someValue.someOtherMethod(); }
What then is Optional<T> good for?