Java 8 Optional. Why of and ofNullable?

后端 未结 8 1507
旧时难觅i
旧时难觅i 2021-02-07 01:01

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

8条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-02-07 02:00

    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.

提交回复
热议问题