简体   繁体   English

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

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

How can I 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 */
    }
    /* ... */
}

What about isEmpty() ? isEmpty()呢?

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

Be sure to use the parts of && in this order, because java will not proceed to evaluate the second part if the first part of && fails, thus ensuring you will not get a null pointer exception from str.isEmpty() if str is null.请务必按此顺序使用&&的部分,因为如果&&的第一部分失败,java 将不会继续评估第二部分,从而确保如果str为 null,您不会从str.isEmpty()获得空指针异常.

Beware, it's only available since Java SE 1.6.请注意,它仅从 Java SE 1.6 开始可用。 You have to check str.length() == 0 on previous versions.您必须在以前的版本上检查str.length() == 0


To ignore whitespace as well:也忽略空格:

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

(since Java 11 str.trim().isEmpty() can be reduced to str.isBlank() which will also test for other Unicode white spaces) (因为 Java 11 str.trim().isEmpty()可以简化为str.isBlank() ,它也将测试其他 Unicode 空格)

Wrapped in a handy function:包裹在一个方便的功能中:

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

Becomes:变成:

if( !empty( str ) )

Use org.apache.commons.lang.StringUtils使用org.apache.commons.lang.StringUtils

I like to use Apache commons-lang for these kinds of things, and especially the StringUtils utility class:我喜欢将 Apache commons-lang用于这些类型的事情,尤其是StringUtils实用程序类:

import org.apache.commons.lang.StringUtils;

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

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

Just adding Android in here:只需在此处添加 Android:

import android.text.TextUtils;

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

To add to @BJorn and @SeanPatrickFloyd The Guava way to do this is:添加到@BJorn 和@SeanPatrickFloyd Guava 方法是:

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

Commons Lang is more readable at times but I have been slowly relying more on Guava plus sometimes Commons Lang is confusing when it comes to isBlank() (as in what is whitespace or not). Commons Lang 有时更具可读性,但我一直在慢慢地更多地依赖 Guava 加上有时 Commons Lang 在isBlank()令人困惑(例如空白与否)。

Guava's version of Commons Lang isBlank would be: Guava 的 Commons Lang isBlank版本将是:

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

I will say code that doesn't allow "" (empty) AND null is suspicious and potentially buggy in that it probably doesn't handle all cases where is not allowing null makes sense (although for SQL I can understand as SQL/HQL is weird about '' ).我会说不允许"" (empty) AND null是可疑的并且可能有问题,因为它可能无法处理所有不允许null有意义的情况(尽管对于 SQL 我可以理解为 SQL/HQL 是关于'' ) 很奇怪。

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

alternatively或者

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

or或者

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

Note: The second check (first and second alternatives) assumes str is not null.注意:第二个检查(第一个和第二个选项)假定 str 不为空。 It's ok only because the first check is doing that (and Java doesn't does the second check if the first is false)!没关系,因为第一次检查是这样做的(如果第一次检查为假,Java 不会进行第二次检查)!

IMPORTANT: DON'T use == for string equality.重要提示:不要将 == 用于字符串相等。 == checks the pointer is equal, not the value. == 检查指针是否相等,而不是值。 Two strings can be in different memory addresses (two instances) but have the same value!两个字符串可以位于不同的内存地址(两个实例)但具有相同的值!

Almost every library I know defines a utility class called StringUtils , StringUtil or StringHelper , and they usually include the method you are looking for.我知道的几乎每个库都定义了一个名为StringUtilsStringUtilStringHelper的实用程序类,它们通常包含您正在寻找的方法。

My personal favorite is Apache Commons / Lang , where in the StringUtils class, you get both the我个人最喜欢的是Apache Commons / Lang ,在StringUtils类中,您可以同时获得

  1. StringUtils.isEmpty(String) and the StringUtils.isEmpty(String)
  2. StringUtils.isBlank(String) method StringUtils.isBlank(String)方法

(The first checks whether a string is null or empty, the second checks whether it is null, empty or whitespace only) (第一个检查字符串是否为空或空,第二个检查它是否为空、空或空格)

There are similar utility classes in Spring, Wicket and lots of other libs. Spring、Wicket 和许多其他库中也有类似的实用程序类。 If you don't use external libraries, you might want to introduce a StringUtils class in your own project.如果您不使用外部库,您可能希望在您自己的项目中引入一个 StringUtils 类。


Update: many years have passed, and these days I'd recommend using Guava 's Strings.isNullOrEmpty(string) method.更新:很多年过去了,现在我建议使用GuavaStrings.isNullOrEmpty(string)方法。

This works for me:这对我有用:

import com.google.common.base.Strings;

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

Returns true if the given string is null or is the empty string.如果给定的字符串为 null 或为空字符串,则返回 true。

Consider normalizing your string references with nullToEmpty.考虑使用 nullToEmpty 规范化您的字符串引用。 If you do, you can use String.isEmpty() instead of this method, and you won't need special null-safe forms of methods like String.toUpperCase either.如果这样做,您可以使用 String.isEmpty() 代替此方法,并且您也不需要像 String.toUpperCase 这样的特殊空安全形式的方法。 Or, if you'd like to normalize "in the other direction," converting empty strings to null, you can use emptyToNull.或者,如果您想“在另一个方向”标准化,将空字符串转换为 null,您可以使用 emptyToNull。

怎么样:

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

There is a new method in : String#isBlank 有一个新方法: String#isBlank

Returns true if the string is empty or contains only white space codepoints, otherwise false.如果字符串为空或仅包含空白代码点,则返回 true,否则返回 false。

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

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

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

This could be combined with Optional to check if string is null or empty这可以与Optional结合使用以检查字符串是否为空或空

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

String#isBlank 字符串#isBlank

Use Apache StringUtils' isNotBlank method like使用 Apache StringUtils 的 isNotBlank 方法,例如

StringUtils.isNotBlank(str)

It will return true only if the str is not null and is not empty.仅当 str 不为 null 且不为空时,它才会返回 true。

You should use org.apache.commons.lang3.StringUtils.isNotBlank() or org.apache.commons.lang3.StringUtils.isNotEmpty .您应该使用org.apache.commons.lang3.StringUtils.isNotBlank()org.apache.commons.lang3.StringUtils.isNotEmpty The decision between these two is based on what you actually want to check for.这两者之间的决定基于您实际想要检查的内容。

The isNotBlank() checks that the input parameter is: isNotBlank()检查输入参数是否为:

  • not Null,不为空,
  • not the empty string ("")不是空字符串 ("")
  • not a sequence of whitespace characters (" ")不是空白字符序列 (" ")

The isNotEmpty() checks only that the input parameter is isNotEmpty()仅检查输入参数是否为

  • not null不为空
  • not the Empty String ("")不是空字符串 ("")

Returns true or false based on input根据输入返回真或假

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

If you don't want to include the whole library;如果您不想包含整个库; just include the code you want from it.只需包含您想要的代码。 You'll have to maintain it yourself;你必须自己维护它; but it's a pretty straight forward function.但这是一个非常直接的功能。 Here it is copied from commons.apache.org这里是从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;
}

It is a bit too late, but here is a functional style of checking:现在有点晚了,但这里有一种功能性的检查方式:

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

For completeness: If you are already using the Spring framework , the StringUtils provide the method为了完整起见:如果您已经在使用 Spring 框架,则StringUtils提供了该方法

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

Returns: true if the String is not null and has length返回: 如果 String 不为 null 且具有长度,则为 true

as well as the method以及方法

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

Returns: true if the String is not null, its length is greater than 0, and it does not contain whitespace only返回: 如果 String 不为 null,其长度大于 0,并且不只包含空格,则返回 true

test equals with an empty string and null in the same conditional: test 等于空字符串和相同条件下的 null:

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

Does not throws NullPointerException if str is null, since Object.equals() returns false if arg is null .如果 str 为 null 则不抛出NullPointerException ,因为Object.equals()如果 arg 为null则返回 false 。

the other construct str.equals("") would throw the dreaded NullPointerException .另一个构造str.equals("")会抛出可怕的NullPointerException Some might consider bad form using a String literal as the object upon wich equals() is called but it does the job.有些人可能会认为使用 String 文字的形式不好,因为调用了equals()的对象,但它可以完成工作。

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

Simple solution :简单的解决方案:

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

I've made my own utility function to check several strings at once, rather than having an if statement full of if(str != null && !str.isEmpty && str2 != null && !str2.isEmpty) .我已经创建了自己的实用程序函数来一次检查多个字符串,而不是让 if 语句充满if(str != null && !str.isEmpty && str2 != null && !str2.isEmpty) This is the function:这是函数:

public class StringUtils{

    public static boolean areSet(String... strings)
    {
        for(String s : strings)
            if(s == null || s.isEmpty)
                return false;

        return true;
    }   

}

so I can simply write:所以我可以简单地写:

if(!StringUtils.areSet(firstName,lastName,address)
{
    //do something
}

You can use StringUtils.isEmpty(), It will result true if the string is either null or empty.您可以使用 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");
 }

will result in会导致

str1 is null or empty str1 为 null 或为空

str2 is null or empty str2 为 null 或为空

As seanizer said above, Apache StringUtils is fantastic for this, if you were to include guava you should do the following;正如 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 **/
}

May I also recommend that you refer to the columns in your result set by name rather than by index, this will make your code much easier to maintain.我还建议您按名称而不是按索引引用结果集中的列,这将使您的代码更易于维护。

In case you are using Java 8 and want to have a more Functional Programming approach, you can define a Function that manages the control and then you can reuse it and apply() whenever is needed.如果您使用的是 Java 8 并希望采用更多的函数式编程方法,您可以定义一个管理控件的Function ,然后您可以在需要时重用它和apply()

Coming to practice, you can define the Function as在实践中,您可以将Function定义为

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

Then, you can use it by simply calling the apply() method as:然后,您可以通过简单地调用apply()方法来使用它:

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

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

If you prefer, you can define a Function that checks if the String is empty and then negate it with !如果您愿意,您可以定义一个Function来检查String是否为空,然后使用! . .

In this case, the Function will look like as :在这种情况下, Function将如下所示:

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

Then, you can use it by simply calling the apply() method as:然后,您可以通过简单地调用apply()方法来使用它:

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

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

With Java 8 Optional you can do:使用Java 8 Optional,您可以执行以下操作:

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

In this expression, you will handle String s that consist of spaces as well.在此表达式中,您还将处理由空格组成的String

To check if a string is not empty you can check if it is null but this doesn't account for a string with whitespace.要检查字符串是否不为空,您可以检查它是否为null但这不考虑带有空格的字符串。 You could use str.trim() to trim all the whitespace and then chain .isEmpty() to ensure that the result is not empty.您可以使用str.trim()修剪所有空格,然后链接.isEmpty()以确保结果不为空。

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

I would advise Guava or Apache Commons according to your actual need.我会根据您的实际需要建议 Guava 或 Apache Commons。 Check the different behaviors in my example code:检查我的示例代码中的不同行为:

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

Result:结果:
Apache:阿帕奇:
a is blank a 为空
b is blank b 为空
c is blank c 为空
Google:谷歌:
b is NullOrEmpty b 是空或空
c is NullOrEmpty c 是 NullOrEmpty

Simply, to ignore white space as well:简单地说,也要忽略空格:

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

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

StringUtils.hasLength(str)

Consider the below example, I have added 4 test cases in main method.考虑下面的例子,我在 main 方法中添加了 4 个测试用例。 three test cases will pass when you follow above commented snipts.当您按照上面的注释片段进行操作时,三个测试用例将通过。

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

BUT test case 4 will return true(it has white space before null) which is wrong:但是测试用例 4 将返回 true(它在 null 之前有空格),这是错误的:

String stringWhiteSpaceWithNull = " null"; // test case 4

We have to add below conditions to make it work propper:我们必须添加以下条件以使其正常工作:

!passedStr.trim().equals("null")

If you use Spring framework then you can use method:如果您使用 Spring 框架,那么您可以使用方法:

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

This method accepts any Object as an argument, comparing it to null and the empty String.此方法接受任何对象作为参数,将其与 null 和空字符串进行比较。 As a consequence, this method will never return true for a non-null non-String object.因此,对于非 null 的非 String 对象,此方法永远不会返回 true。

The better way to handle null in the string is,处理字符串中的 null 的更好方法是,

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

In short,简而言之,

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

To check on if all the string attributes in an object is empty(Instead of using !=null on all the field names following java reflection api approach检查对象中的所有字符串属性是否为空(而不是在遵循 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;
}

This method would return true if all the String field values are blank,It would return false if any one values is present in the String attributes如果所有 String 字段值都为空,则此方法将返回 true,如果 String 属性中存在任何一个值,则此方法将返回 false

I've encountered a situation where I must check that "null" (as a string) must be regarded as empty.我遇到过一种情况,我必须检查“null”(作为字符串)是否必须被视为空。 Also white space and an actual null must return true.此外,空格和实际空值必须返回 true。 I've finally settled on the following function...我终于确定了以下功能......

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

In case you need to validate your method parameters you can use follow simple method如果您需要验证您的方法参数,您可以使用以下简单方法

public class StringUtils {

    static boolean anyEmptyString(String ... strings) {
        return Stream.of(strings).anyMatch(s -> s == null || s.isEmpty());
    }

}

Example:例子:

public String concatenate(String firstName, String lastName) {
    if(StringUtils.anyBlankString(firstName, lastName)) {
        throw new IllegalArgumentException("Empty field found");
    }
    return firstName + " " + lastName;
}

If anyone using springboot, then the following option might be helpful,如果有人使用 springboot,那么以下选项可能会有所帮助,

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

TL;DR长话短说

java.util.function.Predicate is a Functional interface representing a boolean-valued Function . java.util.function.Predicate是一个函数接口,表示一个布尔值 Function

Predicate offers several static and default methods which allow to perform logical operations AND && , OR || Predicate提供了几个staticdefault方法,允许执行逻辑操作AND && , OR || , NOT ! NOT and chain conditions in a fluent way.并以流畅的方式链接条件。

Logical condition "not empty && not null" can be expressed in the following way:逻辑条件“not empty && not null”可以用下面的方式表示:

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

Or, alternatively:或者,或者:

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

Or:要么:

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

Predicate.equal() is your friend Predicate.equal()是你的朋友

Static method Predicate.isEqual() expects a reference to the target object for equality comparison ( an empty string in this case ). Static 方法Predicate.isEqual()需要对目标 object 的引用以进行相等比较(在本例中为空字符串)。 This comparison is not hostile to null , which means isEqual() performs a null-check internally as well as utility method Objects.equals(Object, Object) , so that comparison of null and null would return true without raising an exception.这种比较对null没有敌意,这意味着isEqual()在内部以及实用方法Objects.equals(Object, Object) ) 执行空检查,因此nullnull的比较将返回true而不会引发异常。

A quote from the Javadoc :来自Javadoc的引述:

Returns:退货:

a predicate that tests if two arguments are equal according to Objects.equals(Object, Object)根据Objects.equals(Object, Object)测试两个 arguments 是否相等的谓词

The predicate the compares the given element against the null can be written as:将给定元素与null进行比较的谓词可以写为:

Predicate.isEqual(null)

Predicate.or() OR || Predicate.or()或 ||

Default method Predicate.or() allows chaining the conditions relationship among which can be expressed through logical OR ||默认方法Predicate.or()允许链接条件关系,条件关系可以通过逻辑OR ||表示. .

That's how we can combine the two conditions: empty ||这就是我们如何结合这两个条件:|| null null

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

Now we need to negate this predicate现在我们需要否定这个谓词

Predicate.not() & Predicate.negete() Predicate.not() & Predicate.negete()

To perform the logical negation, we have two options: static method not() and default method negate() .要执行逻辑否定,我们有两个选项: static方法not()default方法negate()

Here's how resulting predicates might be written:以下是结果谓词的写法:

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

Note that in this case the type of the predicate Predicate.isEqual(null) would be inferred as Predicate<Object> since null gives no clue to the compiler what should be the type of the argument, and we can resolve this issue using a so-called Type-witness <String>isEqual() .请注意,在这种情况下,谓词Predicate.isEqual(null)的类型将被推断为Predicate<Object>因为null没有向编译器提供参数类型应该是什么的线索,我们可以使用 so 解决此问题-称为类型见证<String>isEqual()

Or, alternatively或者,或者

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

* Note: String::isEmpty can be also written as ""::equals , and if you need to check whether the string is Blank (contains various forms of unprintable characters or empty) you can use method reference String::isBlank . *注意: String::isEmpty也可以写成""::equals如果需要检查字符串是否为空(包含各种 forms 不可打印字符或为空)可以使用方法参考String::isBlank And if you need to verify a few more conditions, you can add as many as you need by chaining them via or() and and() methods.如果您需要验证更多条件,则可以通过or()and()方法将它们链接起来,根据需要添加任意数量的条件。

Usage Example使用示例

Predicate is used an argument of such method as Stream.filter() , Collection.removeIf() , Collectors.partitioningBy() , etc. and you can create your custom ones. Predicate用作Stream.filter()Collection.removeIf()Collectors.partitioningBy()等方法的参数,您可以创建自定义的。

Consider the following example:考虑以下示例:

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: 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