如何检查一个字符串既不是 null
也不是空的?
public void doStuff(String str)
{
if (str != null && str != "**here I want to check the 'str' is empty or not**")
{
/* handle empty string */
}
/* ... */
}
如何检查一个字符串既不是 null
也不是空的?
public void doStuff(String str)
{
if (str != null && str != "**here I want to check the 'str' is empty or not**")
{
/* handle empty string */
}
/* ... */
}
我已经编写了一个自己的实用函数来一次性检查多个字符串,而不是使用一个if语句包含 if(str != null && !str.isEmpty && str2 != null && !str2.isEmpty)
。 这是这个函数:
public class StringUtils{
public static boolean areSet(String... strings)
{
for(String s : strings)
if(s == null || s.isEmpty)
return false;
return true;
}
}
if(!StringUtils.areSet(firstName,lastName,address)
{
//do something
}
areSet(String... strings)
,这样就不需要创建数组来调用它了:if(!StringUtils.areSet(firstName, lastName, address))
。 - westonnull
,但这并不能考虑到只有空格的字符串。你可以使用str.trim()
去除所有的空格,然后链式调用.isEmpty()
来确保结果不为空。if(str != null && !str.trim().isEmpty()) { /* do your stuffs here */ }
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 为空或为空字符串
str2 为空或为空字符串
isNotBlank
。 - Engineer2021如果您正在使用Spring Boot,则以下代码将完成任务
StringUtils.hasLength(str)
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");
}
}
}
结果:
Apache:
a 为空白
b 为空白
c 为空白
Google:
b 为 NullOrEmpty
c 为 NullOrEmpty
考虑下面的例子,我在主方法中添加了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")
if (str == null || str.trim().length() == 0) {
// str is empty
} else {
// str is not empty
}
java.util.function.Predicate
是一个代表布尔类型函数的函数接口。
Predicate
提供了一些静态(static)
和默认(default)
方法,允许以流畅的方式执行逻辑操作AND
&&、OR
||、NOT
!并链接条件。
逻辑条件“非空且非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()
方法内部执行了空值检查以及实用方法Objects.equals(Object,Object)
,因此将null
与null
进行比较将返回true
而不会引发异常。
来自Javadoc的一句话:
返回:
一个谓词,根据
Objects.equals(Object,Object)
测试两个参数是否相等
比较给定元素与null
的谓词可以编写如下:
Predicate.isEqual(null)
Predicate.or()
或者 ||Predicate.or()
是默认方法,它允许链式组合多个条件,并通过逻辑运算符 OR
|| 表示它们之间的关系。
下面演示了如何将两个条件组合起来:空值||Null
Predicate.isEqual(null).or(String::isEmpty)
现在我们需要否定这个谓词
Predicate.not()
& Predicate.negete()
要进行逻辑否定,我们有两种选择:static
方法 not()
和default
方法 negate()
。
下面是可能的结果谓词的写法:
public static final Predicate<String> NON_EMPTY_NON_NULL =
Predicate.<String>isEqual(null).or(String::isEmpty).negate();
Predicate.isEqual(null)
将被推断为 Predicate<Object>
,因为 null
并没有给编译器提供关于参数类型的线索。我们可以使用所谓的类型见证 <String>isEqual()
来解决这个问题。public static final Predicate<String> NON_EMPTY_NON_NULL =
Predicate.not(Predicate.<String>isEqual(null).or(String::isEmpty));
*注意:String::isEmpty
也可以写成""::equals
,如果您需要检查字符串是否为空(包含各种形式的不可打印字符或空),则可以使用方法引用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
public static final Predicate<String> NON_EMPTY_NON_NULL = Predicate.not(Predicate.isEqual(null).or(String::isEmpty));
返回 "静态上下文中不能引用非静态方法"。 - mellow-yellow<String>.isEqual
来修复上面的问题,像这样 public static final Predicate<String> NON_EMPTY_NON_NULL = Predicate.not(Predicate.<String>isEqual(null).or(String::isEmpty));
- mellow-yellowPredicate.isEqual(null)
的类型会被编译器推断为 Predicate<? extends Object>
,因此我们需要显式提供类型。已更正。 - Alexander Ivanchenkoorg.springframework.util.StringUtils.isEmpty(@Nullable Object str);
这个方法接受任何对象作为参数,将其与null和空字符串进行比较。因此,对于非null的非字符串对象,该方法永远不会返回true。
StringUtils
的文档明确指出:“主要用于框架内部使用;考虑使用 Apache 的 Commons Lang 获取更全面的字符串实用程序套件。” - Fredrik Jonsénimport static org.springframework.util.StringUtils.hasLength;
if (hasLength(str)) {
// do stuff
}
PreparedStatement
等代替通过字符串连接原语构建 SQL 查询。这样可以避免各种注入漏洞,而且更易读等。 - polygenelubricantsPredicate.<String>isEqual(null).or(String::isEmpty).negate()
,具体解释请参考这里。 - Alexander Ivanchenko