检查一个字符串是否既不为null也不为空。

561

如何检查一个字符串既不是 null 也不是空的?

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

8
最好使用 PreparedStatement 等代替通过字符串连接原语构建 SQL 查询。这样可以避免各种注入漏洞,而且更易读等。 - polygenelubricants
2
你可以创建一个类来检查空值或空对象。这将有助于提高可重用性。http://stackoverflow.com/a/16833309/1490962 - Bhushankumar Lilapara
此条件可以用java.util.function.Predicate表达,如下所示:Predicate.<String>isEqual(null).or(String::isEmpty).negate(),具体解释请参考这里 - Alexander Ivanchenko
35个回答

2

我已经编写了一个自己的实用函数来一次性检查多个字符串,而不是使用一个if语句包含 if(str != null && !str.isEmpty && str2 != 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
}

2
最好使用签名:areSet(String... strings),这样就不需要创建数组来调用它了:if(!StringUtils.areSet(firstName, lastName, address)) - weston

2
要检查一个字符串是否不为空,你可以检查它是否为null,但这并不能考虑到只有空格的字符串。你可以使用str.trim()去除所有的空格,然后链式调用.isEmpty()来确保结果不为空。
if(str != null && !str.trim().isEmpty()) { /* do your stuffs here */ }

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


或者直接使用 isNotBlank - Engineer2021

2
如果您正在使用Spring Boot,则以下代码将完成任务:

如果您正在使用Spring Boot,则以下代码将完成任务

StringUtils.hasLength(str)

1
我建议根据您的实际需求选择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 为空白
Google:
b 为 NullOrEmpty
c 为 NullOrEmpty


1

考虑下面的例子,我在主方法中添加了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")

1
简单来说,也要忽略空格:
if (str == null || str.trim().length() == 0) {
    // str is empty
} else {
    // str is not empty
}

1

简明扼要

java.util.function.Predicate是一个代表布尔类型函数函数接口

Predicate提供了一些静态(static)默认(default)方法,允许以流畅的方式执行逻辑操作AND &&OR ||NOT !并链接条件。

逻辑条件“非空且非null”可用以下方式表示:

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

或者,另一种选择:

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

或者:

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

Predicate.equal() 是你的好朋友

静态方法Predicate.isEqual()期望接收一个目标对象的引用用于相等比较(在这种情况下为一个空字符串)。这个比较不会对null持敌意态度,这意味着isEqual()方法内部执行了空值检查以及实用方法Objects.equals(Object,Object),因此将nullnull进行比较将返回true而不会引发异常。

来自Javadoc的一句话:

返回:

一个谓词,根据Objects.equals(Object,Object)测试两个参数是否相等

比较给定元素与null的谓词可以编写如下:

Predicate.isEqual(null)

Predicate.or() 或者 ||

Predicate.or() 是默认方法,它允许链式组合多个条件,并通过逻辑运算符 OR || 表示它们之间的关系。

下面演示了如何将两个条件组合起来:空值||Null

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

现在我们需要否定这个谓词

Predicate.not() & Predicate.negete()

要进行逻辑否定,我们有两种选择:static 方法 not()default 方法 negate()

下面是可能的结果谓词的写法:

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

请注意,在这种情况下,谓词的类型 Predicate.isEqual(null) 将被推断为 Predicate<Object>,因为 null 并没有给编译器提供关于参数类型的线索。我们可以使用所谓的类型见证 <String>isEqual() 来解决这个问题。
或者,另一种方法是:
public static final Predicate<String> NON_EMPTY_NON_NULL =
    Predicate.not(Predicate.<String>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

public static final Predicate<String> NON_EMPTY_NON_NULL = Predicate.not(Predicate.isEqual(null).or(String::isEmpty)); 返回 "静态上下文中不能引用非静态方法"。 - mellow-yellow
显然,您可以通过添加 <String>.isEqual 来修复上面的问题,像这样 public static final Predicate<String> NON_EMPTY_NON_NULL = Predicate.not(Predicate.<String>isEqual(null).or(String::isEmpty)); - mellow-yellow
@mellow-yellow 你说得对,如果没有类型见证,Predicate.isEqual(null) 的类型会被编译器推断为 Predicate<? extends Object>,因此我们需要显式提供类型。已更正。 - Alexander Ivanchenko

0
如果您使用Spring框架,那么您可以使用以下方法:
org.springframework.util.StringUtils.isEmpty(@Nullable Object str);

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


1
请注意,StringUtils 的文档明确指出:“主要用于框架内部使用;考虑使用 Apache 的 Commons Lang 获取更全面的字符串实用程序套件。” - Fredrik Jonsén

0
如果有人在使用Spring Boot,那么以下选项可能会很有帮助:
import static org.springframework.util.StringUtils.hasLength;

if (hasLength(str)) {
  // do stuff
}


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接