Should Optional.ofNullable() be used for null check?

后端 未结 3 761
一向
一向 2020-12-19 04:33

Which null-check is preferable?

Optional.ofNullable(port).ifPresent(settings::setPort);

or

if (port != null) {
   settings.         


        
3条回答
  •  梦毁少年i
    2020-12-19 05:34

    Although, the snippet you have posted in the question is just a simple way to avoid the ugly null-check, yet is valid, correct and null-safe. Follow your personal preference in this case.

    The real power of Optional are the following methods:

    • Optional::filter(Predicate predicate) which applies a filter on a present value.
    • Optional::map(Function mapper) which applies a mapping function on a present value.

    As example, let's say you want to get another value from port to add to the list and avoid the NPE if port is null:

    Optional.ofNullable(port).map(port::getSomeValue).ifPresent(settings::setPort);
    

    Moreover, please, avoid the following meaningless substitution of null-check I see often:

    if (Optional.ofNullable(port).isPresent()) {
        settings.setPort(port);
    }
    

提交回复
热议问题