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

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

当前回答

根据您的实际需要,我建议您选择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

其他回答

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

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

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

简而言之,

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

简单的解决方法:

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

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

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

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

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