Best way to verify string is empty or null

前端 未结 13 813
野的像风
野的像风 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条回答
  •  萌比男神i
    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 notBlank(String s) {
      return s == null || s.chars().allMatch(Character::isWhitepace))
        ? Optional.empty()
        : Optional.of(s);
    }
    
    ...
    
    notBlank(myStr).orElse("some default")
    

提交回复
热议问题