Check whether a string is not null and not empty

后端 未结 30 2458
予麋鹿
予麋鹿 2020-11-22 02:13

How can I check whether a string is not null and not empty?

public void doStuff(String str)
{
    if (str != null && str != \"**here I want to check          


        
30条回答
  •  不要未来只要你来
    2020-11-22 03:00

    There is a new method in java-11: String#isBlank

    Returns true if the string is empty or contains only white space codepoints, otherwise false.

    jshell> "".isBlank()
    $7 ==> true
    
    jshell> " ".isBlank()
    $8 ==> true
    
    jshell> " ! ".isBlank()
    $9 ==> false
    

    This could be combined with Optional to check if string is null or empty

    boolean isNullOrEmpty = Optional.ofNullable(str).map(String::isBlank).orElse(true);
    

    String#isBlank

提交回复
热议问题