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

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

当前回答

import android.text.TextUtils;

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

其他回答

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

字符串#是空白

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

另外

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

or

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

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

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

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

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;
}

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

正如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 **/
}

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