Best way to verify string is empty or null

2020-02-23 05:20发布

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?

12条回答
地球回转人心会变
2楼-- · 2020-02-23 05:56

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")
查看更多
我欲成王,谁敢阻挡
3楼-- · 2020-02-23 05:58

springframework library Check whether the given String is empty.

f(StringUtils.isEmpty("")) {
    //.... String is blank or null
}
查看更多
疯言疯语
4楼-- · 2020-02-23 06:01

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.

查看更多
forever°为你锁心
5楼-- · 2020-02-23 06:03

Just to show java 8's stance to remove null values.

String s = Optional.ofNullable(myString).orElse("");
if (s.trim().isEmpty()) {
    ...
}

Makes sense if you can use Optional<String>.

查看更多
手持菜刀,她持情操
6楼-- · 2020-02-23 06:03

This one from Google Guava could check out "null and empty String" in the same time.

Strings.isNullOrEmpty("Your string.");

Add a dependency with Maven

<dependency>
  <groupId>com.google.guava</groupId>
  <artifactId>guava</artifactId>
  <version>20.0</version>
</dependency>

with Gradle

dependencies {
  compile 'com.google.guava:guava:20.0'
}
查看更多
ゆ 、 Hurt°
7楼-- · 2020-02-23 06:03

You can make use of Optional and Apache commons Stringutils library

Optional.ofNullable(StringUtils.noEmpty(string1)).orElse(string2);

here it will check if the string1 is not null and not empty else it will return string2

查看更多
登录 后发表回答