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

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

当前回答

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

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

其他回答

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

StringUtils.hasLength(str)

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

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

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

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

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

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

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


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

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

博士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