检查字符串是否不为 Null 且不为 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 */
}
/* ... */
}
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(30)
检查对象中的所有字符串属性是否为空(而不是在遵循 java 反射 api 方法的所有字段名称上使用 !=null 。
如果所有字符串字段值为空,则此方法将返回 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
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
TL;DR
java.util.function.Predicate
是一个函数接口,表示布尔值函数。Predicate
提供了几种static
和default
方法,允许执行逻辑运算AND
&&< /strong>、OR
||、NOT
! 以及以流畅的方式链接条件。逻辑条件“notempty&¬null”可以用以下方式表示:
或者,或者:
或者:
Predicate.equal()
是你的朋友
静态方法
Predicate.isEqual()
需要对目标对象的引用以进行相等比较(在本例中为空字符串)。此比较对null
没有敌意,这意味着isEqual()
在内部执行null-check实用方法Objects.equals(Object, Object)
,这样null
和null
的比较将返回true
,而无需引发异常。引用Javadoc:
将给定元素与
null
进行比较的谓词可以写为:谓词.or()
或 ||默认方法
Predicate.or()
允许链接条件关系,条件关系之间可以通过逻辑OR
||来表达。这就是我们如何组合两个条件:empty || null
现在我们需要否定这个谓词
Predicate.not( )
&Predicate.negete()
要执行逻辑否定,我们有两个选项:
static
方法not()
和 <代码>默认方法<代码>negate()。下面是结果谓词的编写方式:
注意,在这种情况下,谓词的类型
Predicate.isEqual(null)
将是推断为Predicate
或者,
*注意:
String::isEmpty
也可以写成""::equals
, < em>如果需要检查字符串是否为Blank(包含各种形式的不可打印字符或空),可以使用方法参考String::isBlank
。 如果您需要验证更多条件,您可以通过通过链接它们来添加所需数量的条件or()
和and()
方法。使用示例
Predicate
用作Stream.filter()
等方法的参数,Collection.removeIf()
、Collectors.partitioningBy()
等,您可以创建自定义的。考虑以下示例:
输出:
TL;DR
java.util.function.Predicate
is a Functional interface representing a boolean-valued Function.Predicate
offers severalstatic
anddefault
methods which allow to perform logical operationsAND
&&,OR
||,NOT
! and chain conditions in a fluent way.Logical condition "not empty && not null" can be expressed in the following way:
Or, alternatively:
Or:
Predicate.equal()
is your friendStatic method
Predicate.isEqual()
expects a reference to the target object for equality comparison (an empty string in this case). This comparison is not hostile tonull
, which meansisEqual()
performs a null-check internally as well as utility methodObjects.equals(Object, Object)
, so that comparison ofnull
andnull
would returntrue
without raising an exception.A quote from the Javadoc:
The predicate the compares the given element against the
null
can be written as:Predicate.or()
OR ||Default method
Predicate.or()
allows chaining the conditions relationship among which can be expressed through logicalOR
||.That's how we can combine the two conditions: empty || null
Now we need to negate this predicate
Predicate.not()
&Predicate.negete()
To perform the logical negation, we have two options:
static
methodnot()
anddefault
methodnegate()
.Here's how resulting predicates might be written:
Note that in this case the type of the predicate
Predicate.isEqual(null)
would be inferred asPredicate<Object>
sincenull
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
*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 referenceString::isBlank
. And if you need to verify a few more conditions, you can add as many as you need by chaining them viaor()
andand()
methods.Usage Example
Predicate
is used an argument of such method asStream.filter()
,Collection.removeIf()
,Collectors.partitioningBy()
, etc. and you can create your custom ones.Consider the following example:
Output:
考虑下面的例子,我在 main 方法中添加了 4 个测试用例。当您按照上面评论的片段进行操作时,三个测试用例将会通过。
但是测试用例 4 将返回 true(它在 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.
BUT test case 4 will return true(it has white space before null) which is wrong:
We have to add below conditions to make it work propper:
如果您使用Spring框架,那么您可以使用方法:
该方法接受任何对象作为参数,将其与null和空字符串进行比较。因此,对于非空非 String 对象,此方法永远不会返回 true。
If you use Spring framework then you can use method:
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.
简单地说,也忽略空白:
Simply, to ignore white space as well:
我会根据您的实际需要建议 Guava 或 Apache Commons。检查我的示例代码中的不同行为:
结果:
阿帕奇:
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:
Result:
Apache:
a is blank
b is blank
c is blank
Google:
b is NullOrEmpty
c is NullOrEmpty
要检查字符串是否不为空,您可以检查它是否为
null
但这不考虑带有空格的字符串。您可以使用str.trim()
修剪所有空格,然后链接.isEmpty()
以确保结果不为空。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 usestr.trim()
to trim all the whitespace and then chain.isEmpty()
to ensure that the result is not empty.使用 Java 8 可选,您可以执行以下操作:
在此表达式中,您还将处理由空格组成的
String
。With Java 8 Optional you can do:
In this expression, you will handle
String
s that consist of spaces as well.如果您使用 Spring Boot 那么下面的代码将完成这项工作
If you are using Spring Boot then below code will do the Job
如果您使用 Java 8 并且想要采用更多函数式编程方法,您可以定义一个管理控件的
Function
,然后您可以重用它并apply()
每当需要的时候。在实践中,您可以将
Function
定义为然后,您可以通过简单地调用
apply()
方法来使用它:如果您愿意,您可以定义一个
函数
检查String
是否为空,然后使用!
对其求反。在这种情况下,
Function
将如下所示:然后,您可以通过简单地调用
apply()
方法来使用它,如下所示: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 andapply()
whenever is needed.Coming to practice, you can define the
Function
asThen, you can use it by simply calling the
apply()
method as:If you prefer, you can define a
Function
that checks if theString
is empty and then negate it with!
.In this case, the
Function
will look like as :Then, you can use it by simply calling the
apply()
method as:我创建了自己的实用程序函数来一次检查多个字符串,而不是使用充满
if(str != null && !str.isEmpty && str2 != null & 的 if 语句。 &!str2.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)
. This is the function:so I can simply write:
您可以使用 StringUtils.isEmpty(),如果字符串为 null 或空,则结果为 true。
将导致
str1 为 null 或为空
str2 为 null 或为空
You can use StringUtils.isEmpty(), It will result true if the string is either null or empty.
will result in
str1 is null or empty
str2 is null or empty
正如上面 Seanizer 所说,Apache StringUtils 对此非常有用,如果您要包含番石榴,您应该执行以下操作;
我还建议您按名称而不是索引引用结果集中的列,这将使您的代码更易于维护。
As seanizer said above, Apache StringUtils is fantastic for this, if you were to include guava you should do the following;
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.
简单的解决方案:
Simple solution :
在同一条件中测试等于空字符串和 null:
如果 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:
Does not throws
NullPointerException
if str is null, sinceObject.equals()
returns false if arg isnull
.the other construct
str.equals("")
would throw the dreadedNullPointerException
. Some might consider bad form using a String literal as the object upon wichequals()
is called but it does the job.Also check this answer: https://stackoverflow.com/a/531825/1532705
如果你不想包含整个库;只需包含您想要的代码即可。您必须自己维护它;但这是一个非常简单的函数。这里它是从 commons.apache.org
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
您应该使用 org.apache.commons.lang3.StringUtils.isNotBlank() 或 org.apache.commons.lang3.StringUtils.isNotEmpty 。这两者之间的决定取决于您实际想要检查的内容。
isNotBlank() 检查输入参数是否为:
不是空白 org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringUtils.html#isNotEmpty(java.lang.CharSequence)" rel="noreferrer">isNotEmpty() 仅检查输入参数不
You should use
org.apache.commons.lang3.StringUtils.isNotBlank()
ororg.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:
The isNotEmpty() checks only that the input parameter is
使用 Apache StringUtils 的 isNotBlank 方法,
仅当 str 不为 null 且不为空时,它才会返回 true。
Use Apache StringUtils' isNotBlank method like
It will return true only if the str is not null and is not empty.
您可以使用函数式检查:
You can use the functional style of checking:
根据输入返回 true 或 false
Returns true or false based on input
怎么样:
How about:
为了完整起见:如果您已经使用 Spring 框架,则 StringUtils 提供方法
以及方法
For completeness: If you are already using the Spring framework, the StringUtils provide the method
as well as the method
java-11:
String#isBlank
这可以与
Optional
结合使用来检查字符串是否为null或空String#isBlank
There is a new method in java-11:
String#isBlank
This could be combined with
Optional
to check if string is null or emptyString#isBlank
这对我有用:
This works for me:
我知道的几乎每个库都定义了一个名为
StringUtils
、StringUtil
或StringHelper
的实用程序类,它们通常包含您正在寻找的方法。我个人最喜欢的是 Apache Commons / Lang,其中 StringUtils 类,您将获得(第一个检查字符串是否为 null 或空,第二个检查字符串是否为 null、空或仅空格)
还有类似的实用程序Spring、Wicket 和许多其他库中的类。如果您不使用外部库,您可能想在自己的项目中引入 StringUtils 类。
更新:很多年过去了,现在我建议使用 Guava 的
Strings.isNullOrEmpty(string)
方法。Almost every library I know defines a utility class called
StringUtils
,StringUtil
orStringHelper
, 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(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.或者
注意:
第二个检查(第一个和第二个选择)假设 str 不为空。这是可以的,只是因为第一个检查正在执行此操作(如果第一个检查为 false,Java 不会执行第二个检查)!
重要提示:不要使用 == 来表示字符串相等。 == 检查指针是否相等,而不是值。两个字符串可以位于不同的内存地址(两个实例),但具有相同的值!
alternatively
or
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!
要添加@BJorn和@SeanPatrickFloyd,Guava的方法是:
Commons Lang有时更具可读性,但我一直在慢慢地更多地依赖Guava,而且有时Commons Lang在涉及
isBlank() (比如什么是空格或不是空格)。
Guava 的 Commons Lang
isBlank
版本是:我会说不允许
""
(空)ANDnull< 的代码/code> 是可疑的,并且可能存在错误,因为它可能无法处理所有不允许
null
有意义的情况(尽管对于 SQL,我可以理解,因为 SQL/HQL 对于' 来说很奇怪) '
)。To add to @BJorn and @SeanPatrickFloyd The Guava way to do this is:
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:I will say code that doesn't allow
""
(empty) ANDnull
is suspicious and potentially buggy in that it probably doesn't handle all cases where is not allowingnull
makes sense (although for SQL I can understand as SQL/HQL is weird about''
).只需在此处添加 Android:
Just adding Android in here:
使用 org.apache。 commons.lang.StringUtils
我喜欢使用 Apache commons-lang 来做这些事情,尤其是 StringUtils 实用程序类:
Use org.apache.commons.lang.StringUtils
I like to use Apache commons-lang for these kinds of things, and especially the StringUtils utility class:
isEmpty() 怎么样? ?
请务必按此顺序使用
&&
部分,因为如果&&
的第一部分失败,java 将不会继续计算第二部分,从而确保如果str
为空,您不会从str.isEmpty()
得到空指针异常。请注意,它仅从 Java SE 1.6 起可用。您必须在以前的版本上检查
str.length() == 0
。还要忽略空格:(
因为 Java 11
str.trim().isEmpty()
可以简化为str.isBlank()
,这也将测试其他 Unicode 白色空格)包裹在一个方便的函数中:
变成:
What about 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 fromstr.isEmpty()
ifstr
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:
(since Java 11
str.trim().isEmpty()
can be reduced tostr.isBlank()
which will also test for other Unicode white spaces)Wrapped in a handy function:
Becomes: