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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32567208/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 12:46:15  来源:igfitidea点击:

Best way to verify string is empty or null

javaregexstringtrimis-empty

提问by prash

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.

我相信这之前一定以不同的方式被问过——因为 isEmptyOrNull 是如此普遍,但人们以不同的方式实现它。但我有以下关于最佳可用方法的好奇查询,这对内存和性能都有好处。

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) 之类的库或任何其他选项?

采纳答案by gzak

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

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

回答by GregH

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

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

and

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

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

回答by Joop Eggen

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>.

回答by Evgeniy Dorofeev

Apache Commons Lang has StringUtils.isEmpty(String str)method which returns true if argument is empty or null

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

回答by mavis.chen

This one from Google Guavacould 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'
}

回答by haneenCo

Optional.ofNullable(label)
.map(String::trim)
.map(string -> !label.isEmpty)
.orElse(false)

OR

或者

TextUtils.isNotBlank(label);

TextUtils.isNotBlank(label);

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

最后一个解决方案将检查是否为空并同时修剪 str

回答by simhumileco

Simply and clearly:

简单明了:

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

回答by Adarsh Thimmappa

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.

在大多数情况下,StringUtils.isBlank(str)来自 apache commons 库可以解决它。但是,如果存在被检查的输入字符串在引号内具有空值的情况,则无法检查这种情况。

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.

以我有一个使用String.valueOf(obj)API转换为字符串的输入对象为例。如果 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 失败时,您可能还必须检查此类用例以确保您的验证正确。

回答by gifpif

springframeworklibrary Check whether the given String is empty.

springframework库 检查给定的 String 是否为空。

f(StringUtils.isEmpty(str)) {
    //.... String is blank or null
}

回答by Deepak Pandey

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 string1is not null and not empty else it will return string2

在这里它将检查string1是否不为 null 且不为空,否则将返回string2