In Java 8, transform Optional of an empty String in Optional.empty

后端 未结 6 574
一向
一向 2021-02-02 06:34

Given a String I need to get an Optional, whereby if the String is null or empty the result would be Optional.empty. I can do it this way:

String ppo = \"\";
Opt         


        
6条回答
  •  离开以前
    2021-02-02 07:02

    You can use map :

    String ppo="";
    Optional ostr = Optional.ofNullable(ppo)
                                    .map(s -> s.isEmpty()?null:s);
    System.out.println(ostr.isPresent()); // prints false
    

提交回复
热议问题