繁体   English   中英

检查字符串是否不是 Null 且不为空

[英]Check whether a String is not Null and not Empty

如何检查字符串是否不是null且不为空?

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

isEmpty()呢?

if(str != null && !str.isEmpty())

请务必按此顺序使用&&的部分,因为如果&&的第一部分失败,java 将不会继续评估第二部分,从而确保如果str为 null,您不会从str.isEmpty()获得空指针异常.

请注意,它仅从 Java SE 1.6 开始可用。 您必须在以前的版本上检查str.length() == 0


也忽略空格:

if(str != null && !str.trim().isEmpty())

(因为 Java 11 str.trim().isEmpty()可以简化为str.isBlank() ,它也将测试其他 Unicode 空格)

包裹在一个方便的功能中:

public static boolean empty( final String s ) {
  // Null-safe, short-circuit evaluation.
  return s == null || s.trim().isEmpty();
}

变成:

if( !empty( str ) )

使用org.apache.commons.lang.StringUtils

我喜欢将 Apache commons-lang用于这些类型的事情,尤其是StringUtils实用程序类:

import org.apache.commons.lang.StringUtils;

if (StringUtils.isNotBlank(str)) {
    ...
} 

if (StringUtils.isBlank(str)) {
    ...
} 

只需在此处添加 Android:

import android.text.TextUtils;

if (!TextUtils.isEmpty(str)) {
...
}

添加到@BJorn 和@SeanPatrickFloyd Guava 方法是:

Strings.nullToEmpty(str).isEmpty(); 
// or
Strings.isNullOrEmpty(str);

Commons Lang 有时更具可读性,但我一直在慢慢地更多地依赖 Guava 加上有时 Commons Lang 在isBlank()令人困惑(例如空白与否)。

Guava 的 Commons Lang isBlank版本将是:

Strings.nullToEmpty(str).trim().isEmpty()

我会说不允许"" (empty) AND null是可疑的并且可能有问题,因为它可能无法处理所有不允许null有意义的情况(尽管对于 SQL 我可以理解为 SQL/HQL 是关于'' ) 很奇怪。

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

或者

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

或者

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

注意:第二个检查(第一个和第二个选项)假定 str 不为空。 没关系,因为第一次检查是这样做的(如果第一次检查为假,Java 不会进行第二次检查)!

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

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

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

  1. StringUtils.isEmpty(String)
  2. StringUtils.isBlank(String)方法

(第一个检查字符串是否为空或空,第二个检查它是否为空、空或空格)

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


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

这对我有用:

import com.google.common.base.Strings;

if (!Strings.isNullOrEmpty(myString)) {
       return myString;
}

如果给定的字符串为 null 或为空字符串,则返回 true。

考虑使用 nullToEmpty 规范化您的字符串引用。 如果这样做,您可以使用 String.isEmpty() 代替此方法,并且您也不需要像 String.toUpperCase 这样的特殊空安全形式的方法。 或者,如果您想“在另一个方向”标准化,将空字符串转换为 null,您可以使用 emptyToNull。

怎么样:

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

有一个新方法: String#isBlank

如果字符串为空或仅包含空白代码点,则返回 true,否则返回 false。

jshell> "".isBlank()
$7 ==> true

jshell> " ".isBlank()
$8 ==> true

jshell> " ! ".isBlank()
$9 ==> false

这可以与Optional结合使用以检查字符串是否为空或空

boolean isNullOrEmpty = Optional.ofNullable(str).map(String::isBlank).orElse(true);

字符串#isBlank

使用 Apache StringUtils 的 isNotBlank 方法,例如

StringUtils.isNotBlank(str)

仅当 str 不为 null 且不为空时,它才会返回 true。

您应该使用org.apache.commons.lang3.StringUtils.isNotBlank()org.apache.commons.lang3.StringUtils.isNotEmpty 这两者之间的决定基于您实际想要检查的内容。

isNotBlank()检查输入参数是否为:

  • 不为空,
  • 不是空字符串 ("")
  • 不是空白字符序列 (" ")

isNotEmpty()仅检查输入参数是否为

  • 不为空
  • 不是空字符串 ("")

根据输入返回真或假

Predicate<String> p = (s)-> ( s != null && !s.isEmpty());
p.test(string);

如果您不想包含整个库; 只需包含您想要的代码。 你必须自己维护它; 但这是一个非常直接的功能。 这里是从commons.apache.org复制的

    /**
 * <p>Checks if a String is whitespace, empty ("") or null.</p>
 *
 * <pre>
 * StringUtils.isBlank(null)      = true
 * StringUtils.isBlank("")        = true
 * StringUtils.isBlank(" ")       = true
 * StringUtils.isBlank("bob")     = false
 * StringUtils.isBlank("  bob  ") = false
 * </pre>
 *
 * @param str  the String to check, may be null
 * @return <code>true</code> if the String is null, empty or whitespace
 * @since 2.0
 */
public static boolean isBlank(String str) {
    int strLen;
    if (str == null || (strLen = str.length()) == 0) {
        return true;
    }
    for (int i = 0; i < strLen; i++) {
        if ((Character.isWhitespace(str.charAt(i)) == false)) {
            return false;
        }
    }
    return true;
}

现在有点晚了,但这里有一种功能性的检查方式:

Optional.ofNullable(str)
    .filter(s -> !(s.trim().isEmpty()))
    .ifPresent(result -> {
       // your query setup goes here
    });

为了完整起见:如果您已经在使用 Spring 框架,则StringUtils提供了该方法

org.springframework.util.StringUtils.hasLength(String str)

返回: 如果 String 不为 null 且具有长度,则为 true

以及方法

org.springframework.util.StringUtils.hasText(String str)

返回: 如果 String 不为 null,其长度大于 0,并且不只包含空格,则返回 true

test 等于空字符串和相同条件下的 null:

if(!"".equals(str) && str != null) {
    // do stuff.
}

如果 str 为 null 则不抛出NullPointerException ,因为Object.equals()如果 arg 为null则返回 false 。

另一个构造str.equals("")会抛出可怕的NullPointerException 有些人可能会认为使用 String 文字的形式不好,因为调用了equals()的对象,但它可以完成工作。

还要检查这个答案: https : //stackoverflow.com/a/531825/1532705

简单的解决方案:

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

我已经创建了自己的实用程序函数来一次检查多个字符串,而不是让 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
}

您可以使用 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 为 null 或为空

str2 为 null 或为空

正如 seanizer 上面所说,Apache StringUtils 在这方面非常棒,如果您要包含番石榴,您应该执行以下操作;

public List<Employee> findEmployees(String str, int dep) {
 Preconditions.checkState(StringUtils.isNotBlank(str), "Invalid input, input is blank or null");
 /** code here **/
}

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

如果您使用的是 Java 8 并希望采用更多的函数式编程方法,您可以定义一个管理控件的Function ,然后您可以在需要时重用它和apply()

在实践中,您可以将Function定义为

Function<String, Boolean> isNotEmpty = s -> s != null && !"".equals(s)

然后,您可以通过简单地调用apply()方法来使用它:

String emptyString = "";
isNotEmpty.apply(emptyString); // this will return false

String notEmptyString = "StackOverflow";
isNotEmpty.apply(notEmptyString); // this will return true

如果您愿意,您可以定义一个Function来检查String是否为空,然后使用! .

在这种情况下, Function将如下所示:

Function<String, Boolean> isEmpty = s -> s == null || "".equals(s)

然后,您可以通过简单地调用apply()方法来使用它:

String emptyString = "";
!isEmpty.apply(emptyString); // this will return false

String notEmptyString = "StackOverflow";
!isEmpty.apply(notEmptyString); // this will return true

使用Java 8 Optional,您可以执行以下操作:

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

在此表达式中,您还将处理由空格组成的String

要检查字符串是否不为空,您可以检查它是否为null但这不考虑带有空格的字符串。 您可以使用str.trim()修剪所有空格,然后链接.isEmpty()以确保结果不为空。

    if(str != null && !str.trim().isEmpty()) { /* do your stuffs here */ }

我会根据您的实际需要建议 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");
    }
  }
}

结果:
阿帕奇:
a 为空
b 为空
c 为空
谷歌:
b 是空或空
c 是 NullOrEmpty

简单地说,也要忽略空格:

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

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

StringUtils.hasLength(str)

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

如果您使用 Spring 框架,那么您可以使用方法:

org.springframework.util.StringUtils.isEmpty(@Nullable Object str);

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

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

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

简而言之,

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

检查对象中的所有字符串属性是否为空(而不是在遵循 java 反射 api 方法的所有字段名称上使用 !=null

private String name1;
private String name2;
private String name3;

public boolean isEmpty()  {

    for (Field field : this.getClass().getDeclaredFields()) {
        try {
            field.setAccessible(true);
            if (field.get(this) != null) {
                return false;
            }
        } catch (Exception e) {
            System.out.println("Exception occurred in processing");
        }
    }
    return true;
}

如果所有 String 字段值都为空,则此方法将返回 true,如果 String 属性中存在任何一个值,则此方法将返回 false

我遇到过一种情况,我必须检查“null”(作为字符串)是否必须被视为空。 此外,空格和实际空值必须返回 true。 我终于确定了以下功能......

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

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

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

如果有人使用 springboot,那么以下选项可能会有所帮助,

import static org.springframework.util.StringUtils.hasLength;
if (hasLength(str)) {
  // do stuff
}

长话短说

java.util.function.Predicate是一个函数接口,表示一个布尔值 Function

Predicate提供了几个staticdefault方法,允许执行逻辑操作AND && , OR || NOT 并以流畅的方式链接条件。

逻辑条件“not empty && not null”可以用下面的方式表示:

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

或者,或者:

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

要么:

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

Predicate.equal()是你的朋友

Static 方法Predicate.isEqual()需要对目标 object 的引用以进行相等比较(在本例中为空字符串)。 这种比较对null没有敌意,这意味着isEqual()在内部以及实用方法Objects.equals(Object, Object) ) 执行空检查,因此nullnull的比较将返回true而不会引发异常。

来自Javadoc的引述:

退货:

根据Objects.equals(Object, Object)测试两个 arguments 是否相等的谓词

将给定元素与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没有向编译器提供参数类型应该是什么的线索,我们可以使用 so 解决此问题-称为类型见证<String>isEqual()

或者,或者

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

*注意: String::isEmpty也可以写成""::equals如果需要检查字符串是否为空(包含各种 forms 不可打印字符或为空)可以使用方法参考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);

Output:

* foo
* bar
* baz
import android.text.TextUtils;

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM