I have a question regarding Java 8\'s Optional, the purpose of which is to tackle NullPointerException
exceptions.
The question is, what is the reason for h
Why would people opt for Optional instead of normal if-else method for null checking?
The main point of Optional
class is to provide a mean for performing null safe mapping operations.
employeeOptional.map(Employee::getName).map(String::toUpperCase).ifPresent(upperCasedNameConsumer)
The expression above can replace a cascade of if-else
statements in a single readable expression.
Optional.of
provides an assertion for the given argument to be a null-null
value, otherwise, you can opt for Optional.ofNullable
if you are not sure about the input.
I strongly recommend you to read the javadoc for Optional
class for more optional chaining methods that you can use for your advantage.