Best way to verify string is empty or null

前端 未结 13 748
野的像风
野的像风 2020-12-14 15:30

i am sure this must have been asked before in different ways - as isEmptyOrNull is so common yet people implement it differently. but i have below curious query in terms of

相关标签:
13条回答
  • 2020-12-14 15:51

    With the openJDK 11 you can use the internal validation to check if the String is null or just white spaces

    import jdk.internal.joptsimple.internal.Strings;
    ...
    
    String targetString;
    if (Strings.isNullOrEmpty(tragetString)) {}
    
    0 讨论(0)
  • 2020-12-14 15:53

    Haven't seen any fully-native solutions, so here's one:

    return str == null || str.chars().allMatch(Character::isWhitespace);
    

    Basically, use the native Character.isWhitespace() function. From there, you can achieve different levels of optimization, depending on how much it matters (I can assure you that in 99.99999% of use cases, no further optimization is necessary):

    return str == null || str.length() == 0 || str.chars().allMatch(Character::isWhitespace);
    

    Or, to be really optimal (but hecka ugly):

    int len;
    if (str == null || (len = str.length()) == 0) return true;
    for (int i = 0; i < len; i++) {
      if (!Character.isWhitespace(str.charAt(i))) return false;
    }
    return true;
    

    One thing I like to do:

    Optional<String> notBlank(String s) {
      return s == null || s.chars().allMatch(Character::isWhitepace))
        ? Optional.empty()
        : Optional.of(s);
    }
    
    ...
    
    notBlank(myStr).orElse("some default")
    
    0 讨论(0)
  • 2020-12-14 15:55

    To detect if a string is null or empty, you can use the following without including any external dependencies on your project and still keeping your code simple/clean:

    if(myString==null || myString.isEmpty()){
        //do something
    }
    

    or if blank spaces need to be detected as well:

    if(myString==null || myString.trim().isEmpty()){
        //do something
    }
    

    you could easily wrap these into utility methods to be more concise since these are very common checks to make:

    public final class StringUtils{
    
        private StringUtils() { }   
    
        public static bool isNullOrEmpty(string s){
            if(s==null || s.isEmpty()){
                return true;
            }
            return false;
        }
    
        public static bool isNullOrWhiteSpace(string s){
            if(s==null || s.trim().isEmpty()){
                return true;
            }
            return false;
        }
    }
    

    and then call these methods via:

    if(StringUtils.isNullOrEmpty(myString)){...}

    and

    if(StringUtils.isNullOrWhiteSpace(myString)){...}

    0 讨论(0)
  • 2020-12-14 16:00

    In most of the cases, StringUtils.isBlank(str) from apache commons library would solve it. But if there is case, where input string being checked has null value within quotes, it fails to check such cases.

    Take an example where I have an input object which was converted into string using String.valueOf(obj) API. In case obj reference is null, String.valueOf returns "null" instead of null.

    When you attempt to use, StringUtils.isBlank("null"), API fails miserably, you may have to check for such use cases as well to make sure your validation is proper.

    0 讨论(0)
  • 2020-12-14 16:01
    Optional.ofNullable(label)
    .map(String::trim)
    .map(string -> !label.isEmpty)
    .orElse(false)
    

    OR

    TextUtils.isNotBlank(label);

    the last solution will check if not null and trimm the str at the same time

    0 讨论(0)
  • 2020-12-14 16:02

    Useful method from Apache Commons:

     org.apache.commons.lang.StringUtils.isBlank(String str)
    

    https://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/StringUtils.html#isBlank(java.lang.String)

    0 讨论(0)
提交回复
热议问题