javaregexstringtrimis-empty

Best way to verify string is empty or null


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 best available approach which is good for memory and performance both.

1) Below does not account for all spaces like in case of empty XML tag

return inputString==null || inputString.length()==0;

2) Below one takes care but trim can eat some performance + memory

return inputString==null || inputString.trim().length()==0;

3) Combining one and two can save some performance + memory (As Chris suggested in comments)

return inputString==null || inputString.trim().length()==0 || inputString.trim().length()==0;

4) Converted to pattern matcher (invoked only when string is non zero length)

private static final Pattern p = Pattern.compile("\\s+");

return inputString==null || inputString.length()==0 || p.matcher(inputString).matches();

5) Using libraries like - Apache Commons (StringUtils.isBlank/isEmpty) or Spring (StringUtils.isEmpty) or Guava (Strings.isNullOrEmpty) or any other option?


Solution

  • 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")