Why use Optional.of over Optional.ofNullable?

后端 未结 4 1270
悲哀的现实
悲哀的现实 2020-11-28 01:20

When using the Java 8 Optional class, there are two ways in which a value can be wrapped in an optional.

String foobar = ;
         


        
4条回答
  •  Happy的楠姐
    2020-11-28 02:04

    This depends upon scenarios.

    Let's say you have some business functionality and you need to process something with that value further but having null value at time of processing would impact it.

    Then, in that case, you can use Optional.

    String nullName = null;
    
    String name = Optional.ofNullable(nullName)
                          .map()
                          .orElse("Default value in case of null");
    

提交回复
热议问题