检查字符串是否为空,而不是空。

时间:2022-12-19 07:23:14

How can I check whether a string is not null and not empty?

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

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

24 个解决方案

#1


786  

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. isempty()中不会出现空指针异常。

Beware, it's only available since Java SE 1.6. You have to check str.length() == 0 on previous versions.

注意,它只从Java SE 1.6开始可用。在以前的版本中,必须检查string .length() = 0。


To ignore whitespace as well:

也可以忽略空白:

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

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

#2


177  

Use org.apache.commons.lang.StringUtils

I like to use Apache commons-lang for these kinds of things, and especially the StringUtils utility class:

我喜欢使用Apache common -lang来处理这类事情,尤其是StringUtils实用程序类:

import org.apache.commons.lang.StringUtils;

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

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

#3


102  

Just adding Android in here:

在这里添加Android:

import android.text.TextUtils;

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

#4


39  

To add to @BJorn and @SeanPatrickFloyd The Guava way to do this is:

加到@BJorn和@SeanPatrickFloyd的番石榴方式是:

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有时更容易读懂,但我一直在慢慢地更依赖于番石榴,有时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 '').

我要说,不允许“”(空)和null的代码是可疑的,而且可能存在bug,因为它可能不能处理不允许null的所有情况(尽管对于SQL,我可以理解为SQL/HQL很奇怪)。

#5


31  

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. It's ok only because the first check is doing that (and Java doesn't does the second check if the first is false)!

注意:第二个检查(第一个和第二个选项)假设str不是null。这是可以的,因为第一个检查正在这样做(如果第一个检查是假的,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!

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

#6


23  

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.

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

Consider normalizing your string references with 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. Or, if you'd like to normalize "in the other direction," converting empty strings to null, you can use emptyToNull.

考虑将字符串引用规范化为nullToEmpty。如果您这样做,您可以使用String. isempty()代替这个方法,并且不需要特殊的null-safe格式的方法,比如String。包含。或者,如果您希望“在另一个方向上”规范化,将空字符串转换为null,您可以使用emptyToNull。

#7


20  

Almost every library I know defines a utility class called StringUtils, StringUtil or StringHelper, and they usually include the method you are looking for.

我所知道的几乎每个库都定义了一个实用类StringUtils、StringUtil或StringHelper,它们通常包含您正在查找的方法。

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
  2. StringUtils.isEmpty(字符串)
  3. StringUtils.isBlank(String) method
  4. StringUtils.isBlank(String)方法

(The first checks whether a string is null or empty, the second checks whether it is null, empty or whitespace only)

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

There are similar utility classes in Spring, Wicket and lots of other libs. If you don't use external libraries, you might want to introduce a StringUtils class in your own project.

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


Update: many years have passed, and these days I'd recommend using Guava's Strings.isNullOrEmpty(string) method.

更新:多年过去了,现在我建议使用番石榴的string . isnullorempty (string)方法。

#8


10  

How about:

如何:

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

#9


6  

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为非空且非空时,它才返回true。

#10


4  

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

#11


4  

You should use org.apache.commons.lang3.StringUtils.isNotBlank() or org.apache.commons.lang3.StringUtils.isNotEmpty. The decision between these two is based on what you actually want to check for.

你应该使用org.apache.common .lang3. stringutils . isnotblank()或org.apache.common .lang3. stringutils . isnotempty。这两者之间的决定是基于您实际想要检查的内容。

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 ("")
  • 不是空字符串(")

#12


3  

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

#13


2  

As seanizer said above, Apache StringUtils is fantastic for this, if you were to include guava you should do the following;

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

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.

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

#14


2  

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为空,则不抛出NullPointerException,因为如果arg为空,则objec .equals()返回false。

the other construct str.equals("") would throw the dreaded 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(“”)将抛出一个可怕的NullPointerException。有些人可能会认为使用字符串文字作为调用wich equals()上的对象的不良形式,但它确实有效。

Also check this answer: https://*.com/a/531825/1532705

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

#15


2  

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). This is the function:

我创建了自己的实用函数来一次检查几个字符串,而不是使用一个满是if(str != null & !str)的if语句。空&& 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;
    }   

}

so I can simply write:

所以我可以这样写:

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

#16


1  

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为空或空

#17


1  

I would advise Guava or Apache Commons according to your actual need. Check the different behaviors in my example code:

我会根据您的实际需要,建议您使用番石榴或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");
    }
  }
}

Result:
Apache:
a is blank
b is blank
c is blank
Google:
b is NullOrEmpty
c is NullOrEmpty

结果:Apache: a为空b为空c为空谷歌:b为空c为空

#18


1  

Simple solution :

简单的解决方案:

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

#19


1  

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,并且希望有一个更实用的编程方法,您可以定义一个管理控件的函数,然后您可以在需要时重用它并应用()。

Coming to practice, you can define the Function as

在实践中,可以将函数定义为

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 = "*";
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 !.

如果您愿意,您可以定义一个函数来检查字符串是否为空,然后使用!

In this case, the Function will look like as :

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

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 = "*";
!isEmpty.apply(notEmptyString); // this will return true

#20


1  

Returns true or false based on input

根据输入返回真或假

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

#21


0  

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

返回:如果字符串不是空的,并且有长度,则返回

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

返回:如果字符串不为空,则为true,其长度大于0,且不仅包含空格

#22


0  

Simply, to ignore white space as well:

简单地说,忽略白色空间:

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

#23


0  

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. As a consequence, this method will never return true for a non-null non-String object.

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

#24


0  

With Java 8 Optional you can do:

使用Java 8可选选项,您可以做到:

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 that consist of spaces as well.

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

#1


786  

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. isempty()中不会出现空指针异常。

Beware, it's only available since Java SE 1.6. You have to check str.length() == 0 on previous versions.

注意,它只从Java SE 1.6开始可用。在以前的版本中,必须检查string .length() = 0。


To ignore whitespace as well:

也可以忽略空白:

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

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

#2


177  

Use org.apache.commons.lang.StringUtils

I like to use Apache commons-lang for these kinds of things, and especially the StringUtils utility class:

我喜欢使用Apache common -lang来处理这类事情,尤其是StringUtils实用程序类:

import org.apache.commons.lang.StringUtils;

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

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

#3


102  

Just adding Android in here:

在这里添加Android:

import android.text.TextUtils;

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

#4


39  

To add to @BJorn and @SeanPatrickFloyd The Guava way to do this is:

加到@BJorn和@SeanPatrickFloyd的番石榴方式是:

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有时更容易读懂,但我一直在慢慢地更依赖于番石榴,有时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 '').

我要说,不允许“”(空)和null的代码是可疑的,而且可能存在bug,因为它可能不能处理不允许null的所有情况(尽管对于SQL,我可以理解为SQL/HQL很奇怪)。

#5


31  

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. It's ok only because the first check is doing that (and Java doesn't does the second check if the first is false)!

注意:第二个检查(第一个和第二个选项)假设str不是null。这是可以的,因为第一个检查正在这样做(如果第一个检查是假的,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!

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

#6


23  

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.

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

Consider normalizing your string references with 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. Or, if you'd like to normalize "in the other direction," converting empty strings to null, you can use emptyToNull.

考虑将字符串引用规范化为nullToEmpty。如果您这样做,您可以使用String. isempty()代替这个方法,并且不需要特殊的null-safe格式的方法,比如String。包含。或者,如果您希望“在另一个方向上”规范化,将空字符串转换为null,您可以使用emptyToNull。

#7


20  

Almost every library I know defines a utility class called StringUtils, StringUtil or StringHelper, and they usually include the method you are looking for.

我所知道的几乎每个库都定义了一个实用类StringUtils、StringUtil或StringHelper,它们通常包含您正在查找的方法。

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
  2. StringUtils.isEmpty(字符串)
  3. StringUtils.isBlank(String) method
  4. StringUtils.isBlank(String)方法

(The first checks whether a string is null or empty, the second checks whether it is null, empty or whitespace only)

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

There are similar utility classes in Spring, Wicket and lots of other libs. If you don't use external libraries, you might want to introduce a StringUtils class in your own project.

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


Update: many years have passed, and these days I'd recommend using Guava's Strings.isNullOrEmpty(string) method.

更新:多年过去了,现在我建议使用番石榴的string . isnullorempty (string)方法。

#8


10  

How about:

如何:

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

#9


6  

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为非空且非空时,它才返回true。

#10


4  

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

#11


4  

You should use org.apache.commons.lang3.StringUtils.isNotBlank() or org.apache.commons.lang3.StringUtils.isNotEmpty. The decision between these two is based on what you actually want to check for.

你应该使用org.apache.common .lang3. stringutils . isnotblank()或org.apache.common .lang3. stringutils . isnotempty。这两者之间的决定是基于您实际想要检查的内容。

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 ("")
  • 不是空字符串(")

#12


3  

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

#13


2  

As seanizer said above, Apache StringUtils is fantastic for this, if you were to include guava you should do the following;

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

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.

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

#14


2  

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为空,则不抛出NullPointerException,因为如果arg为空,则objec .equals()返回false。

the other construct str.equals("") would throw the dreaded 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(“”)将抛出一个可怕的NullPointerException。有些人可能会认为使用字符串文字作为调用wich equals()上的对象的不良形式,但它确实有效。

Also check this answer: https://*.com/a/531825/1532705

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

#15


2  

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). This is the function:

我创建了自己的实用函数来一次检查几个字符串,而不是使用一个满是if(str != null & !str)的if语句。空&& 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;
    }   

}

so I can simply write:

所以我可以这样写:

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

#16


1  

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为空或空

#17


1  

I would advise Guava or Apache Commons according to your actual need. Check the different behaviors in my example code:

我会根据您的实际需要,建议您使用番石榴或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");
    }
  }
}

Result:
Apache:
a is blank
b is blank
c is blank
Google:
b is NullOrEmpty
c is NullOrEmpty

结果:Apache: a为空b为空c为空谷歌:b为空c为空

#18


1  

Simple solution :

简单的解决方案:

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

#19


1  

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,并且希望有一个更实用的编程方法,您可以定义一个管理控件的函数,然后您可以在需要时重用它并应用()。

Coming to practice, you can define the Function as

在实践中,可以将函数定义为

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 = "*";
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 !.

如果您愿意,您可以定义一个函数来检查字符串是否为空,然后使用!

In this case, the Function will look like as :

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

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 = "*";
!isEmpty.apply(notEmptyString); // this will return true

#20


1  

Returns true or false based on input

根据输入返回真或假

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

#21


0  

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

返回:如果字符串不是空的,并且有长度,则返回

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

返回:如果字符串不为空,则为true,其长度大于0,且不仅包含空格

#22


0  

Simply, to ignore white space as well:

简单地说,忽略白色空间:

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

#23


0  

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. As a consequence, this method will never return true for a non-null non-String object.

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

#24


0  

With Java 8 Optional you can do:

使用Java 8可选选项,您可以做到:

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 that consist of spaces as well.

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