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

发布于 2024-09-16 15:30:03 字数 255 浏览 6 评论 0原文

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

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(30

千秋岁 2024-09-23 15:30:55

检查对象中的所有字符串属性是否为空(而不是在遵循 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;
}

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

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

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

那一片橙海, 2024-09-23 15:30:54

TL;DR

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

Predicate 提供了几种staticdefault 方法,允许执行逻辑运算 AND &&< /strong>、OR ||NOT ! 以及以流畅的方式链接条件。

逻辑条件“notempty&¬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() 在内部执行null-check实用方法 Objects.equals(Object, Object),这样 nullnull 的比较将返回 true,而无需引发异常。

引用Javadoc

退货:

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

将给定元素与 null 进行比较的谓词可以写为:

Predicate.isEqual(null)

谓词.or() 或 ||

默认方法Predicate.or()允许链接条件关系,条件关系之间可以通过逻辑OR||来表达。

这就是我们如何组合两个条件:empty || null

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

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

Predicate.not( ) & Predicate.negete()

要执行逻辑否定,我们有两个选项:static 方法 not() 和 <代码>默认方法<代码>negate()。

下面是结果谓词的编写方式:

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

注意,在这种情况下,谓词的类型 Predicate.isEqual(null) 将是推断为 Predicatesince null 没有给编译器任何参数类型的线索,我们可以使用所谓的类型见证来解决这个问题 isEqual()

或者,

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

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

TL;DR

java.util.function.Predicate is a Functional interface representing a boolean-valued Function.

Predicate offers several static and default methods which allow to perform logical operations AND &&, OR ||, NOT ! and chain conditions in a fluent way.

Logical condition "not empty && not null" can be expressed in the following way:

Predicate.not(Predicate.<String>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

Static method Predicate.isEqual() expects a reference to the target object for equality comparison (an empty string in this case). 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.

A quote from the Javadoc:

Returns:

a predicate that tests if two arguments are equal according to
Objects.equals(Object, Object)

The predicate the compares the given element against the null can be written as:

Predicate.isEqual(null)

Predicate.or() OR ||

Default method Predicate.or() allows chaining the conditions relationship among which can be expressed through logical OR ||.

That's how we can combine the two conditions: empty || null

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

Now we need to negate this predicate

Predicate.not() & Predicate.negete()

To perform the logical negation, we have two options: static method not() and default method 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().

Or, alternatively

public static final Predicate<String> NON_EMPTY_NON_NULL =
    Predicate.not(Predicate.<String>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. 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.

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.

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:

* foo
* bar
* baz
舞袖。长 2024-09-23 15:30:52

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

Consider the below example, I have added 4 test cases in main method. 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:

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

We have to add below conditions to make it work propper:

!passedStr.trim().equals("null")
看透却不说透 2024-09-23 15:30:51

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

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

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

If you use Spring framework then you can use method:

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.

梦亿 2024-09-23 15:30:49

简单地说,也忽略空白:

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

Simply, to ignore white space as well:

if (str == null || str.trim().length() == 0) {
    // str is empty
} else {
    // str is not empty
}
沩ん囻菔务 2024-09-23 15:30:48

我会根据您的实际需要建议 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 为 Null 或 Empty
c 为 Null 或 Empty

I would advise Guava or Apache Commons according to your actual need. 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
b is blank
c is blank
Google:
b is NullOrEmpty
c is NullOrEmpty

不再见 2024-09-23 15:30:47

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

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

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. You could use str.trim() to trim all the whitespace and then chain .isEmpty() to ensure that the result is not empty.

if(str != null && !str.trim().isEmpty()) { /* do your stuffs here */ }
瀞厅☆埖开 2024-09-23 15:30:46

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

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

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

With Java 8 Optional you can do:

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

In this expression, you will handle Strings that consist of spaces as well.

澉约 2024-09-23 15:30:45

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

StringUtils.hasLength(str)

If you are using Spring Boot then below code will do the Job

StringUtils.hasLength(str)
佼人 2024-09-23 15:30:44

如果您使用 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

如果您愿意,您可以定义一个 函数检查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

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.

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:

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 !.

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:

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

String notEmptyString = "StackOverflow";
!isEmpty.apply(notEmptyString); // this will return true
失眠症患者 2024-09-23 15:30:43

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

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:

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
}

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

You can use StringUtils.isEmpty(), It will result true if the string is either null or empty.

 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

str2 is null or empty

初心未许 2024-09-23 15:30:38

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

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

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

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.

盗心人 2024-09-23 15:30:36

简单的解决方案:

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

Simple solution :

private boolean stringNotEmptyOrNull(String st) {
    return st != null && !st.isEmpty();
}
情感失落者 2024-09-23 15:30:32

在同一条件中测试等于空字符串和 null:

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

如果 str 为 null,则不会抛出 NullPointerException,因为 Object.equals() 如果 arg 为 <,则返回 false代码>空。

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

另请检查此答案:https://stackoverflow.com/a/531825/1532705

test equals with an empty string and null in the same conditional:

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

Does not throws NullPointerException if str is null, since Object.equals() returns false if arg is null.

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.

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

櫻之舞 2024-09-23 15:30:29

如果你不想包含整个库;只需包含您想要的代码即可。您必须自己维护它;但这是一个非常简单的函数。这里它是从 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;
}

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

    /**
 * <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;
}
薄凉少年不暖心 2024-09-23 15:30:26

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

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

  • 不是 Null、
  • 不是空字符串 ("")
  • 字符序列 (" ")

不是空白 org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringUtils.html#isNotEmpty(java.lang.CharSequence)" rel="noreferrer">isNotEmpty() 仅检查输入参数不

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

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.

The isNotBlank() checks that the input parameter is:

  • not Null,
  • not the empty string ("")
  • not a sequence of whitespace characters (" ")

The isNotEmpty() checks only that the input parameter is

  • not null
  • not the Empty String ("")
抚笙 2024-09-23 15:30:24

使用 Apache StringUtils 的 isNotBlank 方法,

StringUtils.isNotBlank(str)

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

Use Apache StringUtils' isNotBlank method like

StringUtils.isNotBlank(str)

It will return true only if the str is not null and is not empty.

孤独岁月 2024-09-23 15:30:22

您可以使用函数式检查:

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

You can use the functional style of checking:

Optional.ofNullable(str)
    .filter(s -> !(s.trim().isEmpty()))
    .ifPresent(result -> {
       // your query setup goes here
    });
梦初启 2024-09-23 15:30:20

根据输入返回 true 或 false

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

Returns true or false based on input

Predicate<String> p = (s)-> ( s != null && !s.isEmpty());
p.test(string);
要走干脆点 2024-09-23 15:30:18

怎么样:

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

How about:

if(str!= null && str.length() != 0 )
对不⑦ 2024-09-23 15:30:17

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

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

返回:
如果字符串不为 null 并且有长度,则为 true

以及方法

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

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

For completeness: If you are already using the Spring framework, the StringUtils provide the method

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

表情可笑 2024-09-23 15:30:15

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

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

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

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

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

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

String#isBlank

There is a new method in : String#isBlank

Returns true if the string is empty or contains only white space codepoints, otherwise 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

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

String#isBlank

笙痞 2024-09-23 15:30:14

这对我有用:

import com.google.common.base.Strings;

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

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

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

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.

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.

入怼 2024-09-23 15:30:12

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

我个人最喜欢的是 Apache Commons / Lang,其中 StringUtils 类,您将获得

  1. StringUtils.isEmpty(字符串)
  2. StringUtils.isBlank(String) 方法

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

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


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

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

My personal favorite is Apache Commons / Lang, where in the StringUtils class, you get both the

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

(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. If you don't use external libraries, you might want to introduce a StringUtils class in your own project.


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

岁月打碎记忆 2024-09-23 15:30:11
str != null && str.length() != 0

或者

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

注意:

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

第二个检查(第一个和第二个选择)假设 str 不为空。这是可以的,只是因为第一个检查正在执行此操作(如果第一个检查为 false,Java 不会执行第二个检查)!

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

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

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!

如果没有你 2024-09-23 15:30:10

要添加@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()

我会说不允许 "" (空)AND null< 的代码/code> 是可疑的,并且可能存在错误,因为它可能无法处理所有不允许 null 有意义的情况(尽管对于 SQL,我可以理解,因为 SQL/HQL 对于 ' 来说很奇怪) ')。

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

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

Guava's version of Commons Lang isBlank would be:

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

调妓 2024-09-23 15:30:09

只需在此处添加 Android:

import android.text.TextUtils;

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

Just adding Android in here:

import android.text.TextUtils;

if (!TextUtils.isEmpty(str)) {
...
}
岁月如刀 2024-09-23 15:30:08

使用 org.apache。 commons.lang.StringUtils

我喜欢使用 Apache commons-lang 来做这些事情,尤其是 StringUtils 实用程序类:

import org.apache.commons.lang.StringUtils;

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

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

Use org.apache.commons.lang.StringUtils

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

import org.apache.commons.lang.StringUtils;

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

if (StringUtils.isBlank(str)) {
    ...
} 
南笙 2024-09-23 15:30:07

isEmpty() 怎么样? ?

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

请务必按此顺序使用 && 部分,因为如果 && 的第一部分失败,java 将不会继续计算第二部分,从而确保如果 str 为空,您不会从 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 ) )

What about 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.

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


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)

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 ) )
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文