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

public void doStuff(String str)
{
    if (str != null && str != "**here I want to check the 'str' is empty or not**")
    {
        /* handle empty string */
    }
    /* ... */
}

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

另外

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

or

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

注意:第二次检查(第一个和第二个替代)假设str不为空。这只是因为第一次检查是这样做的(如果第一次检查为假,Java不会进行第二次检查)!

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

如何:

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

那么isEmpty()呢?

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

请确保按此顺序使用&&的部分,因为如果&&的第一部分失败,java将不会继续计算第二部分,从而确保如果str为空,则不会从str. isempty()获得空指针异常。

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


也可以忽略空白:

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

(从Java 11开始,str.trim().isEmpty()可以简化为str.isBlank(),这也将测试其他Unicode空白)

封装在一个方便的函数中:

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

就变成:

if( !empty( str ) )

使用org.apache.commons.lang.StringUtils

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

import org.apache.commons.lang.StringUtils;

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

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

我知道的几乎每个库都定义了一个名为StringUtils、StringUtil或StringHelper的实用程序类,它们通常包含你正在寻找的方法。

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

StringUtils.isEmpty(字符串)和 StringUtils.isBlank (String)方法

(第一个检查字符串是空的还是空的,第二个检查它是空的,空的还是空白的)

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


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

正如seanizer上面所说,Apache StringUtils在这方面非常出色,如果你要包括guava,你应该做以下工作;

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

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

使用Apache StringUtils的isNotBlank方法

StringUtils.isNotBlank(str)

只有当str不为空时,它才会返回true。

加上@BJorn和@SeanPatrickFloyd的番石榴方法是:

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

Commons Lang有时更具可读性,但我已经慢慢地更多地依赖于Guava,有时Commons Lang在涉及到isBlank()时令人困惑(如什么是空白或不是空白)。

Guava版本的Commons Lang isBlank将是:

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

我会说,代码不允许“”(空)和null是可疑的,潜在的bug,因为它可能无法处理所有不允许null有意义的情况(尽管对于SQL,我可以理解为SQL/HQL是奇怪的”)。

在这里添加Android:

import android.text.TextUtils;

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

如果你不想包含整个库;只包括你想要的代码。你得自己维护;但这是一个很简单的函数。这里是从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;
}

测试等于一个空字符串和null在相同的条件:

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

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

另一个构造str.equals("")会抛出可怕的NullPointerException。有些人可能认为在调用equals()时使用String字面值作为对象是一种糟糕的形式,但它确实完成了这项工作。

还有这个答案:https://stackoverflow.com/a/531825/1532705

这对我来说很管用:

import com.google.common.base.Strings;

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

如果给定字符串为null或为空字符串,则返回true。 考虑用nullToEmpty规范字符串引用。如果你 做,你可以使用String.isEmpty()而不是这个方法,你不会吗 需要特殊的零安全形式的方法,如String.toUpperCase 要么。或者,如果你想“从另一个方向”正常化, 将空字符串转换为null,可以使用emptyToNull。

我已经制作了自己的实用函数来一次检查几个字符串,而不是有一个充满if(str != null && !str的if语句。= 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
}

你可以使用StringUtils.isEmpty(),如果字符串是空的或空的,则结果为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为空或空

Str2为null或空

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

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

非空, 不是空字符串("") 不是空白字符序列(" ")

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

非空 不是空字符串("")

根据您的实际需要,我建议您选择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为空白 谷歌: b为NullOrEmpty c为NullOrEmpty

简单的解决方法:

private boolean stringNotEmptyOrNull(String st) {
    return st != null && !st.isEmpty();
}

为了完整性:如果您已经在使用Spring框架,则StringUtils提供了该方法

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

返回: 如果String不是null并且有长度,则为true

以及方法

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

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

你可以使用函数式检查:

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

简单地说,忽略空白:

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

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

在实践中,您可以将函数定义为

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

如果您愿意,您可以定义一个函数来检查String是否为空,然后用!对其求反。

在这种情况下,函数看起来像:

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

根据输入返回true或false

Predicate<String> p = (s)-> ( s != null && !s.isEmpty());
p.test(string);

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

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

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

使用Java 8可选,你可以做:

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

在这个表达式中,您也将处理由空格组成的字符串。

java-11中有一个新方法:String#isBlank

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

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

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

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

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

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

字符串#是空白

处理字符串中的null更好的方法是,

str!=null && !str.equalsIgnoreCase("null") && !str.isEmpty()

简而言之,

str.length()>0 && !str.equalsIgnoreCase("null")

检查对象中的所有字符串属性是否为空(而不是按照java reflection 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

如果您正在使用Spring Boot,那么下面的代码将完成工作

StringUtils.hasLength(str)
import android.text.TextUtils;

if (!TextUtils.isEmpty(str)||!str.equalsIgnoreCase("") {
    ...
}

我遇到过一种情况,我必须检查“null”(作为字符串)必须被视为空。空格和实际null必须返回true。 我最终确定了下面的函数…

public boolean isEmpty(String testString) {
  return ((null==testString) || "".equals((""+testString).trim()) || "null".equals((""+testString).toLowerCase()));
}

如果你需要验证你的方法参数,你可以使用以下简单的方法

public class StringUtils {

    static boolean anyEmptyString(String ... strings) {
        return Stream.of(strings).anyMatch(s -> s == null || s.isEmpty());
    }

}

例子:

public String concatenate(String firstName, String lastName) {
    if(StringUtils.anyBlankString(firstName, lastName)) {
        throw new IllegalArgumentException("Empty field found");
    }
    return firstName + " " + lastName;
}

要检查字符串是否为空,可以检查它是否为空,但这不能说明有空格的字符串。您可以使用str.trim()来修剪所有空白,然后链接. isempty()以确保结果不为空。

    if(str != null && !str.trim().isEmpty()) { /* do your stuffs here */ }

考虑下面的例子,我在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")

如果有人使用springboot,那么下面的选项可能会有帮助,

import static org.springframework.util.StringUtils.hasLength;
if (hasLength(str)) {
  // do stuff
}

博士TL;

predicate是一个表示布尔值函数的函数接口。

Predicate提供了一些静态和默认方法,允许执行逻辑操作and &&, OR ||, NOT !和链条件在流畅的方式。

逻辑条件“not empty && not null”可以表示为:

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

或者,或者:

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

Or:

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

equal()是你的朋友

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

引用Javadoc的一句话:

返回: 测试两个参数是否相等的谓词 对象。=(对象,对象)

比较给定元素与null值的谓词The可以写成:

Predicate.isEqual(null)

Predicate.or() OR || . OR

默认方法Predicate.or()允许将可以通过逻辑OR ||表示的条件之间的关系链接起来。

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

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

现在我们要对这个谓词求反

Predicate.not() & predicate . neggete ()

要执行逻辑否定,我们有两个选项:静态方法not()和默认方法negate()。

下面是如何编写结果谓词:

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

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

或者,或者

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

*注意:String::isEmpty也可以写成""::equals,如果你需要检查字符串是否为空白(包含各种形式的不可打印字符或空),你可以使用方法引用String::isBlank。如果需要验证更多的条件,可以通过or()和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