Why use Optional.of over Optional.ofNullable?

后端 未结 4 1268
悲哀的现实
悲哀的现实 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条回答
  •  一向
    一向 (楼主)
    2020-11-28 01:55

    In addition, If you know your code should not work if object is null, you can throw exception by using Optional.orElseThrow

    String nullName = null;
    String name = Optional.ofNullable(nullName).orElseThrow(NullPointerException::new);
    

提交回复
热议问题