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

后端 未结 6 598
一向
一向 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 06:41

    With Apache Commons:

    .filter(StringUtils::isNotEmpty)
    
    0 讨论(0)
  • You could use a filter:

    Optional<String> ostr = Optional.ofNullable(ppo).filter(s -> !s.isEmpty());
    

    That will return an empty Optional if ppo is null or empty.

    0 讨论(0)
  • 2021-02-02 06:51

    If you use Guava, you can just do:

    Optional<String> ostr = Optional.ofNullable(Strings.emptyToNull(ppo));
    
    0 讨论(0)
  • 2021-02-02 06:58

    Java 11 answer:

    var optionalString = Optional.ofNullable(str).filter(Predicate.not(String::isBlank));
    

    String::isBlank deals with a broader range of 'empty' characters.

    0 讨论(0)
  • 2021-02-02 06:58

    How about:

    Optional<String> ostr = ppo == null || ppo.isEmpty()
        ? Optional.empty()
        : Optional.of(ppo);
    

    You can put that in a utility method if you need it often, of course. I see no benefit in creating an Optional with an empty string, only to then ignore it.

    0 讨论(0)
  • 2021-02-02 07:02

    You can use map :

    String ppo="";
    Optional<String> ostr = Optional.ofNullable(ppo)
                                    .map(s -> s.isEmpty()?null:s);
    System.out.println(ostr.isPresent()); // prints false
    
    0 讨论(0)
提交回复
热议问题