简体   繁体   English

验证字符串为空或 null 的最佳方法

[英]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.我相信这之前一定以不同的方式被问过——因为 isEmptyOrNull 是如此普遍,但人们以不同的方式实现它。 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 1) 下面没有像空 XML 标签那样考虑所有空格

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

2) Below one takes care but trim can eat some performance + memory 2)下面一个要小心但是trim可以吃一些性能+内存

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

3) Combining one and two can save some performance + memory (As Chris suggested in comments) 3)结合一和二可以节省一些性能+内存(正如克里斯在评论中建议的那样)

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

4) Converted to pattern matcher (invoked only when string is non zero length) 4) 转换为模式匹配器(仅在字符串非零长度时调用)

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? 5) 使用像 - Apache Commons ( StringUtils.isBlank/isEmpty ) 或 Spring ( StringUtils.isEmpty ) 或 Guava ( Strings.isNullOrEmpty ) 或任何其他选项之类的库?

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:要检测字符串是否为 null 或为空,您可以使用以下内容,而无需在您的项目中包含任何外部依赖项,并且仍然保持您的代码简单/干净:

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)){...}

Just to show java 8's stance to remove null values.只是为了表明 java 8 删除空值的立场。

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

Makes sense if you can use Optional<String> .如果您可以使用Optional<String>就有意义。

This one from Google Guava could check out "null and empty String" in the same time.这个来自Google Guava 的可以同时检查“空字符串和空字符串”。

Strings.isNullOrEmpty("Your string.");

Add a dependency with Maven使用 Maven 添加依赖项

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

with Gradle使用 Gradle

dependencies {
  compile 'com.google.guava:guava:20.0'
}

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.基本上,使用原生 Character.isWhitespace() 函数。 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):从那里,您可以实现不同级别的优化,具体取决于它的重要性(我可以向您保证,在 99.99999% 的用例中,不需要进一步优化):

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

Apache Commons Lang 有StringUtils.isEmpty(String str)方法,如果参数为空或为空则返回 true

springframework library Check whether the given String is empty. springframework库 检查给定的 String 是否为空。

f(StringUtils.isEmpty(str)) {
    //.... String is blank or null
}
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最后一个解决方案将检查是否为空并同时修剪 str

In most of the cases, StringUtils.isBlank(str) from apache commons library would solve it.在大多数情况下,来自 apache 公共库的StringUtils.isBlank(str)可以解决它。 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.以我有一个使用String.valueOf(obj) API 转换为字符串的输入对象为例。 In case obj reference is null, String.valueOf returns "null" instead of null.如果 obj 引用为 null,则 String.valueOf 返回“null”而不是 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.当您尝试使用StringUtils.isBlank("null") ,API 惨遭失败,您可能还必须检查此类用例以确保您的验证正确。

With the openJDK 11 you can use the internal validation to check if the String is null or just white spaces使用 openJDK 11,您可以使用内部验证来检查字符串是否为空或只是空格

import jdk.internal.joptsimple.internal.Strings;
...

String targetString;
if (Strings.isNullOrEmpty(tragetString)) {}

Simply and clearly:简单明了:

if (str == null || str.trim().length() == 0) {
    // str is empty
}

You can make use of Optional and Apache commons Stringutils library您可以使用 Optional 和 Apache commons Stringutils 库

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在这里它将检查string1是否不为 null 且不为空,否则将返回string2

If you have to test more than one string in the same validation, you can do something like this:如果您必须在同一个验证中测试多个字符串,您可以执行以下操作:

import java.util.Optional;
import java.util.function.Predicate;
import java.util.stream.Stream;

public class StringHelper {

  public static Boolean hasBlank(String ... strings) {

    Predicate<String> isBlank = s -> s == null || s.trim().isEmpty();

    return Optional
      .ofNullable(strings)
      .map(Stream::of)
      .map(stream -> stream.anyMatch(isBlank))
      .orElse(false);
  }

}

So, you can use this like StringHelper.hasBlank("Hello", null, "", " ") or StringHelper.hasBlank("Hello") in a generic form.因此,您可以像StringHelper.hasBlank("Hello", null, "", " ")StringHelper.hasBlank("Hello")以通用形式使用它。

We can make use of below我们可以利用以下

Optional.ofNullable(result).filter(res -> StringUtils.isNotEmpty(res))
            .ifPresent( s-> val.set(s));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM