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

public void doStuff(String str)
{
    if (str != null && str != "**here I want to check the 'str' is empty or not**")
    {
        /* handle empty 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")

其他回答

简单地说,忽略空白:

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

如何:

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

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

使用Apache StringUtils的isNotBlank方法

StringUtils.isNotBlank(str)

只有当str不为空时,它才会返回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