检查 String 是否不为 Null 且不为空

Check whether a String is not Null and not Empty

提问人: 提问时间:8/30/2010 最后编辑:Alexander Ivanchenko 更新时间:8/18/2023 访问量:1165060

问:

如何检查字符串是否不为空?null

public void doStuff(String str)
{
    if (str != null && str != "**here I want to check the 'str' is empty or not**")
    {
        /* handle empty string */
    }
    /* ... */
}
java 字符串 条件语句 string-comparison 布尔逻辑 java-11

评论

8赞 polygenelubricants 8/30/2010
您可能应该使用 and 等,而不是通过字符串连接基元构造 SQL 查询。避免各种注入漏洞,更具可读性等。PreparedStatement
2赞 Bhushankumar Lilapara 5/30/2013
您可以创建将检查 null 值或 null 对象的类。这将帮助您提高可重用性。stackoverflow.com/a/16833309/1490962
0赞 Alexander Ivanchenko 12/2/2022
此条件可以按以下方式表示为 java.util.function.Predicate如下所述Predicate.<String>isEqual(null).or(String::isEmpty).negate()

答:

35赞 helios 8/30/2010 #1
str != null && str.length() != 0

或者

str != null && !str.equals("")

str != null && !"".equals(str)

注意:第二个检查(第一个和第二个备选方案)假定 str 不为 null。这没关系,因为第一次检查正在这样做(如果第一次检查是假的,Java 不会进行第二次检查)!

重要提示:不要将 == 用于字符串相等。== 检查指针是否相等,而不是值。两个字符串可以位于不同的内存地址(两个实例)中,但具有相同的值!

评论

0赞 arn-arn 3/6/2015
谢谢。。。str.length() 对我有用。我的情况是,在从数据库查询后,我从数组中获取值。即使数据为空,当我执行 str.length 时,它也会给出“1”长度。很奇怪,但谢谢你给我看这个。
0赞 helios 3/13/2015
这与数据库的内部结构有关。要么是 char 字段而不是 varchar 字段(所以它用空格填充),要么数据库不喜欢空字符串。我想最好的方法是在查询之后/查询时预处理这些值(在应用程序稍后的数据访问中)。
0赞 bluelurker 12/10/2015
我认为检查长度比“等于”更好,因为这是一个 O(1) 操作,因为在 String 的情况下缓存了长度。
10赞 codaddict 8/30/2010 #2

怎么样:

if(str!= null && str.length() != 0 )

评论

1赞 Mindwin Remember Monica 5/15/2013
如果 str 为 NULL,则引发 NullPointerException。
14赞 Zach Lysobey 8/15/2013
@Mindwin 那不是真的。它不会执行 if str == null 右侧的代码,从而防止 NullPointerException。(来源: 我刚刚尝试过)&&
1赞 Mindwin Remember Monica 2/18/2014
我纠正了。不会因为羞愧而删除评论,这样 Zach 和 GI Joe 就不会留下无处不在的回复。哈哈。但是很高兴知道,如果您执行其他操作而不是测试内容并在跳过的方法调用上返回布尔值,则此跳过可能会导致逻辑故障。
3赞 user207421 6/24/2016
@Mindwin 很高兴知道你使用的语言实际上是如何工作的。如果您不了解短路评估,要么不使用它,要么最好了解它。
996赞 Colin Hebert 8/30/2010 #3

isEmpty() 呢?

if(str != null && !str.isEmpty())

请务必按此顺序使用 的各部分,因为如果第一部分失败,java 将不会继续计算第二部分,从而确保您不会从 if is null 中获得 null 指针异常。&&&&str.isEmpty()str

请注意,它仅在 Java SE 1.6 之后可用。您必须检查以前的版本。str.length() == 0


同时忽略空格:

if(str != null && !str.trim().isEmpty())

(因为 Java 11 可以简化为它也将测试其他 Unicode 空格)str.trim().isEmpty()str.isBlank()

包装在一个方便的功能中:

public static boolean empty( final String s ) {
  // Null-safe, short-circuit evaluation.
  return s == null || s.trim().isEmpty();
}

成为:

if( !empty( str ) )

评论

83赞 James P. 8/14/2011
请注意,这似乎需要一个 String 实例(非静态)。对 null 引用调用此函数将引发 NullPointerException。isEmpty()
39赞 PapaFreud 11/22/2013
或者 if(str != null && !str.trim().isEmpty()),忽略空格。
0赞 jruzafa 4/29/2014
if((txt.getText().length()) == 0 ) // 从布局中获取元素
37赞 George Maisuradze 11/20/2014
我建议用来检查字符串是空的还是空的。又好又短。TextUtils 类是 Android SDK 的一部分。TextUtils.isEmpty(String)
1赞 ToolmakerSteve 8/28/2015
@user1154390:有时为了清楚起见,明确使用 true 和 false 是值得的,但是当条件返回 true 表示 true 和 false 表示 false 时,它就变得不必要了。简单地说.(str != null && str.length() > 0)
244赞 Romain Linsolas 8/30/2010 #4

使用 org.apache.commons.lang.StringUtils

我喜欢使用 Apache commons-lang 来做这些事情,尤其是 StringUtils 实用程序类:

import org.apache.commons.lang.StringUtils;

if (StringUtils.isNotBlank(str)) {
    ...
} 

if (StringUtils.isBlank(str)) {
    ...
} 

评论

22赞 zengr 8/30/2010
如果你能只使用 isEmpty,Apache commons-lang 不是矫枉过正吗?只是好奇。
21赞 Bozho 8/30/2010
@zengr - 不,因为你肯定会使用其他东西:)
2赞 Romain Linsolas 8/30/2010
@zengr 事实上,如果您只使用 或 ,也许包含第三方库是没有用的。您可以简单地创建自己的实用程序类来提供此类方法。然而,正如 Bozho 所解释的那样,该项目提供了许多有用的方法!isEmptyisBlankcommons-lang
16赞 sdesciencelover 1/30/2013
因为 null 检查也是如此。StringUtils.isNotBlank(str)
4赞 linuxunil 10/26/2018
如果您使用 Spring Framework,这可能已经捆绑在框架的 jar 中。
29赞 Sean Patrick Floyd 8/30/2010 #5

我所知道的几乎每个库都定义了一个名为 , or 的实用程序类,它们通常包含您正在寻找的方法。StringUtilsStringUtilStringHelper

我个人最喜欢的是 Apache Commons / Lang,在 StringUtils 类中,您可以同时获得

  1. StringUtils.isEmpty(String)
  2. StringUtils.isBlank(String) 方法

(第一个检查字符串是 null 还是空,第二个检查它是 null、空还是仅空格)

在 Spring、Wicket 和许多其他库中也有类似的实用程序类。如果不使用外部库,则可能需要在自己的项目中引入 StringUtils 类。


更新:很多年过去了,现在我建议使用 GuavaStrings.isNullOrEmpty(string) 方法。

评论

0赞 vicangel 8/20/2019
我想问你为什么现在推荐这个?我想知道 Strings.isNullOrEmpty(string) 和 StringUtils.isEmpty(String) 之间是否有区别
0赞 Sean Patrick Floyd 8/22/2019
@vicangel Apache Commons 方法充满了我没有要求的假设和东西。有了番石榴,我得到了我想要的东西,没有或多或少
2赞 BjornS 8/30/2010 #6

正如上面所说,Apache StringUtils 在这方面非常棒,如果你要包含番石榴,你应该执行以下操作;

public List<Employee> findEmployees(String str, int dep) {
 Preconditions.checkState(StringUtils.isNotBlank(str), "Invalid input, input is blank or null");
 /** code here **/
}

我还建议您按名称而不是索引引用结果集中的列,这将使您的代码更易于维护。

评论

0赞 Sean Patrick Floyd 8/30/2010
不过,无需使用番石榴的 apache commons,番石榴中也有一个 Strings 类:guava-libraries.googlecode.com/svn/trunk/javadoc/com/google/......
0赞 Adam Gent 10/31/2012
我为新手 Java 用户添加了一些 Guava 示例,这些示例涉及这个问题:stackoverflow.com/a/13146903/318174
7赞 A Null Pointer 11/10/2011 #7

使用 Apache StringUtils 的 isNotBlank 方法,例如

StringUtils.isNotBlank(str)

仅当 str 不为 null 且不为空时,它才会返回 true。

评论

1赞 Alexandr 11/14/2011
实际上,如果 str 在这里为 null,则该语句返回 true
0赞 A Null Pointer 11/14/2011
这是真的,我的坏!相反,使用 apache-commons 的 StringUtils.isNotEmpty(str) 可以完成这项工作。
52赞 Adam Gent 10/31/2012 #8

要添加到@BJorn并@SeanPatrickFloyd番石榴的方法是:

Strings.nullToEmpty(str).isEmpty(); 
// or
Strings.isNullOrEmpty(str);

Commons Lang 有时更具可读性,但我一直在慢慢更多地依赖番石榴,而且有时 Commons Lang 在涉及到(例如什么是空格或不空格)时会令人困惑。isBlank()

Guava 的 Commons Lang 版本是:isBlank

Strings.nullToEmpty(str).trim().isEmpty()

我会说不允许(空)并且的代码是可疑的并且可能存在错误,因为它可能无法处理所有不允许的情况(尽管对于 SQL,我可以理解为 SQL/HQL 很奇怪)。""nullnull''

评论

0赞 Thupten 6/29/2015
第二个番石榴也是。番石榴遵循复数静态类的约定。对于 String,请尝试将 Strings 用于静态方法,例如 isNullOrEmpty(str)。
106赞 phreakhead 1/25/2013 #9

只需在此处添加 Android:

import android.text.TextUtils;

if (!TextUtils.isEmpty(str)) {
...
}

评论

1赞 Nick 12/11/2014
@staticx,Lang 2.0 版中更改了 StringUtils 方法。它不再修剪 CharSequence。该功能在 isBlank() 中可用。
5赞 Tom 4/30/2013 #10

如果您不想包含整个库;只需包含您想要的代码即可。你必须自己维护它;但这是一个非常简单的功能。这里是从 commons.apache.org 复制的

    /**
 * <p>Checks if a String is whitespace, empty ("") or null.</p>
 *
 * <pre>
 * StringUtils.isBlank(null)      = true
 * StringUtils.isBlank("")        = true
 * StringUtils.isBlank(" ")       = true
 * StringUtils.isBlank("bob")     = false
 * StringUtils.isBlank("  bob  ") = false
 * </pre>
 *
 * @param str  the String to check, may be null
 * @return <code>true</code> if the String is null, empty or whitespace
 * @since 2.0
 */
public static boolean isBlank(String str) {
    int strLen;
    if (str == null || (strLen = str.length()) == 0) {
        return true;
    }
    for (int i = 0; i < strLen; i++) {
        if ((Character.isWhitespace(str.charAt(i)) == false)) {
            return false;
        }
    }
    return true;
}
3赞 Mindwin Remember Monica 5/15/2013 #11

test 等于空字符串和 null 在同一个条件中:

if(!"".equals(str) && str != null) {
    // do stuff.
}

如果 str 为 null,则不抛出,因为如果 arg 为 ,则 Object.equals() 返回 false。NullPointerExceptionnull

另一个结构会抛出可怕的.有些人可能会认为使用 String 字面量作为 wich 对象时的不良形式,但它可以完成工作。str.equals("")NullPointerExceptionequals()

还要检查这个答案:https://stackoverflow.com/a/531825/1532705

评论

1赞 amdev 11/20/2018
那么为什么要添加从未达到的代码呢? 已经完成了这项工作str != null!"".equals(str)
25赞 Javatar 7/11/2013 #12

这对我有用:

import com.google.common.base.Strings;

if (!Strings.isNullOrEmpty(myString)) {
       return myString;
}

如果给定字符串为 null 或为空字符串,则返回 true。

请考虑使用 nullToEmpty 规范化字符串引用。如果你 做,你可以使用 String.isEmpty() 而不是这个方法,你不会 需要特殊的 null 安全形式的方法,如 String.toUpperCase 也。或者,如果您想“在另一个方向”上归一化, 将空字符串转换为 null 时,可以使用 emptyToNull。

评论

3赞 Junchen Liu 10/1/2014
<dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> <version>12.0</version> </dependency>
2赞 W.K.S 11/15/2013 #13

我制作了自己的实用函数来一次检查多个字符串,而不是让 if 语句充满 .这是函数:if(str != null && !str.isEmpty && str2 != null && !str2.isEmpty)

public class StringUtils{

    public static boolean areSet(String... strings)
    {
        for(String s : strings)
            if(s == null || s.isEmpty)
                return false;

        return true;
    }   

}

所以我可以简单地写:

if(!StringUtils.areSet(firstName,lastName,address)
{
    //do something
}

评论

2赞 weston 2/11/2014
使用签名会更好:然后可以在不创建数组的情况下调用:areSet(String... strings)if(!StringUtils.areSet(firstName, lastName, address))
2赞 Vivek Vermani 2/12/2014 #14

您可以使用 StringUtils.isEmpty(),如果字符串为 null 或空,则结果为 true。

 String str1 = "";
 String str2 = null;

 if(StringUtils.isEmpty(str)){
     System.out.println("str1 is null or empty");
 }

 if(StringUtils.isEmpty(str2)){
     System.out.println("str2 is null or empty");
 }

将导致

str1 为 null 或为空

str2 为 null 或为空

评论

0赞 Engineer2021 2/15/2014
或者只是使用isNotBlank
7赞 gprasant 4/21/2015 #15

您应该使用 或 .这两者之间的决定基于您实际要检查的内容。org.apache.commons.lang3.StringUtils.isNotBlank()org.apache.commons.lang3.StringUtils.isNotEmpty

isNotBlank() 检查输入参数是否为:

  • 不为空,
  • 不是空字符串 (“”)
  • 不是空格字符序列 (“ ”)

isNotEmpty() 仅检查输入参数是否为

  • 非空
  • 不是空字符串 (“”)
1赞 BlondCode 1/18/2016 #16

我会根据您的实际需要建议 Guava 或 Apache Commons。检查我的示例代码中的不同行为:

import com.google.common.base.Strings;
import org.apache.commons.lang.StringUtils;

/**
 * Created by hu0983 on 2016.01.13..
 */
public class StringNotEmptyTesting {
  public static void main(String[] args){
        String a = "  ";
        String b = "";
        String c=null;

    System.out.println("Apache:");
    if(!StringUtils.isNotBlank(a)){
        System.out.println(" a is blank");
    }
    if(!StringUtils.isNotBlank(b)){
        System.out.println(" b is blank");
    }
    if(!StringUtils.isNotBlank(c)){
        System.out.println(" c is blank");
    }
    System.out.println("Google:");

    if(Strings.isNullOrEmpty(Strings.emptyToNull(a))){
        System.out.println(" a is NullOrEmpty");
    }
    if(Strings.isNullOrEmpty(b)){
        System.out.println(" b is NullOrEmpty");
    }
    if(Strings.isNullOrEmpty(c)){
        System.out.println(" c is NullOrEmpty");
    }
  }
}

结果:Apache:

a 为空 b 为空 c 为空
Google :

b 为 NullOrEmpty
c 为 NullOrEmpty

3赞 Shweta 7/15/2016 #17

简单的解决方案:

private boolean stringNotEmptyOrNull(String st) {
    return st != null && !st.isEmpty();
}
9赞 AntiTiming 4/6/2017 #18

为了完整起见:如果您已经在使用 Spring 框架则 StringUtils 提供了以下方法

org.springframework.util.StringUtils.hasLength(String str)

返回: 如果 String 不为 null 且长度为 true

以及方法

org.springframework.util.StringUtils.hasText(String str)

返回: 如果 String 不为 null,则为 true,其长度大于 0,并且它不包含空格

评论

0赞 Supun Dharmarathne 5/10/2019
我们可以使用 StringUtils.isEmpty(param) 方法。
7赞 pilot 6/7/2017 #19

您可以使用检查的功能样式:

Optional.ofNullable(str)
    .filter(s -> !(s.trim().isEmpty()))
    .ifPresent(result -> {
       // your query setup goes here
    });

评论

2赞 bachph 8/11/2017
我建议使用映射进行修剪,例如: Optional.ofNullable(str) .map(String::trim) .filter(String::isEmpty) .ifPresent(this::setStringMethod);
1赞 simhumileco 10/25/2017 #20

简单地说,也要忽略空格:

if (str == null || str.trim().length() == 0) {
    // str is empty
} else {
    // str is not empty
}
2赞 araknoid 1/23/2018 #21

如果您使用的是 Java 8 并希望采用更函数式编程的方法,您可以定义一个管理控件的方法,然后您可以在需要时重用它。Functionapply()

在实践中,您可以将Function

Function<String, Boolean> isNotEmpty = s -> s != null && !"".equals(s)

然后,只需将方法调用为:apply()

String emptyString = "";
isNotEmpty.apply(emptyString); // this will return false

String notEmptyString = "StackOverflow";
isNotEmpty.apply(notEmptyString); // this will return true

如果您愿意,可以定义一个来检查 是否为空,然后用 否定它。FunctionString!

在本例中,将如下所示:Function

Function<String, Boolean> isEmpty = s -> s == null || "".equals(s)

然后,只需将方法调用为:apply()

String emptyString = "";
!isEmpty.apply(emptyString); // this will return false

String notEmptyString = "StackOverflow";
!isEmpty.apply(notEmptyString); // this will return true

评论

0赞 david.pfx 3/27/2020
这就是我喜欢的做法,当我担心性能成本或副作用时,而且手头没有现成的进口产品。
8赞 Koustubh Mokashi 1/25/2018 #22

根据输入返回 true 或 false

Predicate<String> p = (s)-> ( s != null && !s.isEmpty());
p.test(string);
0赞 Taras Melnyk 1/31/2018 #23

如果你使用Spring框架,那么你可以使用方法:

org.springframework.util.StringUtils.isEmpty(@Nullable Object str);

此方法接受任何 Object 作为参数,并将其与 null 和空 String 进行比较。因此,此方法永远不会为非 null 非 String 对象返回 true。

评论

1赞 Fredrik Jonsén 11/28/2018
请注意,文档明确指出“主要用于框架内的内部使用;考虑使用 Apache 的 Commons Lang 来获得更全面的 String 实用程序套件。StringUtils
2赞 Johnny 5/28/2018 #24

使用 Java 8 Optional,您可以执行以下操作:

public Boolean isStringCorrect(String str) {
    return Optional.ofNullable(str)
            .map(String::trim)
            .map(string -> !str.isEmpty())
            .orElse(false);
}

在此表达式中,您还将处理由空格组成的 s。String

17赞 Anton Balaniuc 6/28/2018 #25

中有一个新方法:String#isBlank

如果字符串为空或仅包含空格代码点,则返回 true,否则返回 false。

jshell> "".isBlank()
$7 ==> true

jshell> " ".isBlank()
$8 ==> true

jshell> " ! ".isBlank()
$9 ==> false

这可以与检查字符串是否为 null 或空结合使用Optional

boolean isNullOrEmpty = Optional.ofNullable(str).map(String::isBlank).orElse(true);

字符串#isBlank

0赞 Lokeshkumar R 1/29/2019 #26

检查对象中的所有字符串属性是否为空(而不是按照 java 反射 api 方法对所有字段名称使用 !=null

private String name1;
private String name2;
private String name3;

public boolean isEmpty()  {

    for (Field field : this.getClass().getDeclaredFields()) {
        try {
            field.setAccessible(true);
            if (field.get(this) != null) {
                return false;
            }
        } catch (Exception e) {
            System.out.println("Exception occurred in processing");
        }
    }
    return true;
}

如果所有 String 字段值都为空,则此方法将返回 true,如果 String 属性中存在任何一个值,则返回 false

2赞 Avinash 2/2/2019 #27

如果您使用的是Spring Boot,则下面的代码将完成这项工作

StringUtils.hasLength(str)
2赞 Raviraj 11/9/2020 #28

要检查字符串是否不为空,您可以检查它是否为空,但这不考虑带有空格的字符串。您可以使用修剪所有空格,然后链接以确保结果不为空。nullstr.trim().isEmpty()

if(str != null && !str.trim().isEmpty()) { /* do your stuffs here */ }
1赞 Amarjit Kushwaha 2/7/2022 #29

考虑下面的示例,我在 main 方法中添加了 4 个测试用例。当您按照上面注释的片段进行操作时,将通过三个测试用例。

public class EmptyNullBlankWithNull {
    public static boolean nullEmptyBlankWithNull(String passedStr) {
        if (passedStr != null && !passedStr.trim().isEmpty() && !passedStr.trim().equals("null")) {
            // TODO when string is null , Empty, Blank
            return true;
        }else{
            // TODO when string is null , Empty, Blank
            return false;
        }
    }

    public static void main(String[] args) {
        String stringNull = null; // test case 1
        String stringEmpty = ""; // test case 2
        String stringWhiteSpace = "  "; // test case 3
        String stringWhiteSpaceWithNull = " null"; // test case 4
        System.out.println("TestCase result:------ "+nullEmptyBlankWithNull(stringWhiteSpaceWithNull));
        
    }
}

但是测试用例 4 将返回 true(它在 null 之前有空格),这是错误的:

String stringWhiteSpaceWithNull = " null"; // test case 4

我们必须添加以下条件才能使其正常工作:

!passedStr.trim().equals("null")
1赞 Alexander Ivanchenko 12/2/2022 #30

TL的;博士

java.util.function.Predicate 是一个 Function 接口,表示布尔值函数

Predicate提供了几种方法,允许以流畅的方式执行逻辑运算&&、||和链条件。staticdefaultANDORNOT

逻辑条件“not empty & not null”可以用以下方式表示:

Predicate.not(Predicate.<String>isEqual(null).or(String::isEmpty));

或者,或者:

Predicate.<String>isEqual(null).or(String::isEmpty).negate();

艺术

Predicate.<String>isEqual(null).or(""::equals).negate();

Predicate.equal() 是你的朋友

静态方法需要对目标对象的引用以进行相等比较(在本例中为空字符串)。这种比较 无关,这意味着在内部执行 null 检查以及实用程序方法,因此 和 的比较将返回而不会引发异常。Predicate.isEqual()nullisEqual()Objects.equals(Object, Object)nullnulltrue

引用 Javadoc 中的一句话:

返回:

一个谓词,用于测试两个参数是否相等,根据Objects.equals(Object, Object)

将给定元素与 进行比较的谓词可以写成:null

Predicate.isEqual(null)

Predicate.or() 中或 ||

默认方法允许链接条件关系,其中可以通过逻辑 ||表示Predicate.or()OR

这就是我们如何组合这两个条件:|| null

Predicate.isEqual(null).or(String::isEmpty)

现在我们需要否定这个谓词

Predicate.not() & Predicate.negete()

要执行逻辑否定,我们有两个选项:method 和 method 。staticnot()defaultnegate()

生成的谓词的编写方式如下:

public static final Predicate<String> NON_EMPTY_NON_NULL =
    Predicate.<String>isEqual(null).or(String::isEmpty).negate();

请注意,在这种情况下,谓词的类型将被推断为因为没有向编译器提供参数类型应该是什么的线索,我们可以使用所谓的 Type-witness 来解决这个问题Predicate.isEqual(null)Predicate<Object>null<String>isEqual()

或者,或者

public static final Predicate<String> NON_EMPTY_NON_NULL =
    Predicate.not(Predicate.<String>isEqual(null).or(String::isEmpty));

*注意:也可以写成如果需要检查字符串是否为空白(包含各种形式的不可打印字符或空),可以使用方法引用如果您需要验证更多条件,您可以通过 和 方法链接它们来添加任意数量的条件 String::isEmpty""::equalsString::isBlankor()and()

使用示例

Predicate使用了 、 、 等方法的参数,您可以创建自定义的参数。Stream.filter()Collection.removeIf()Collectors.partitioningBy()

请看以下示例:

List<String> strings = Stream.of("foo", "bar", "", null, "baz")
    .filter(NON_EMPTY_NON_NULL)
    .map("* "::concat) // append a prefix to make sure that empty string can't sneak in
    .toList();
        
strings.forEach(System.out::println);

输出:

* foo
* bar
* baz

评论

0赞 mellow-yellow 3/8/2023
public static final Predicate<String> NON_EMPTY_NON_NULL = Predicate.not(Predicate.isEqual(null).or(String::isEmpty));返回“无法从静态上下文引用非静态方法”
0赞 mellow-yellow 3/8/2023
显然,您可以通过添加这样的内容来解决上述问题<String>.isEqualpublic static final Predicate<String> NON_EMPTY_NON_NULL = Predicate.not(Predicate.<String>isEqual(null).or(String::isEmpty));
0赞 Alexander Ivanchenko 3/9/2023
@mellow-yellow 你是对的,如果没有类型见证,编译器会推断出 的类型为 ,因此我们需要显式提供类型。修订。Predicate.isEqual(null)Predicate<? extends Object>