这篇文章将讨论如何检查 Java 中的 Collection(Set、List、Map 等)是否为空。
1.使用
isEmpty()
方法
检查 Java 集合是否为空的标准解决方案是调用
isEmpty()
对应集合上的方法。如果集合不包含任何元素,则返回 true。
以下解决方案提供了自定义实现
isEmpty()
和
isNotEmpty()
方法,优雅地处理空输入。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import
java
.
util
.
Set
;
public
class
Main
{
public
static
boolean
isNotEmpty
(
Set
<Integer>
set
)
{
return
set
!=
null
&&
!
set
.
isEmpty
(
)
;
}
public
static
boolean
isEmpty
(
Set
<Integer>
set
)
{
return
set
==
null
||
set
.
isEmpty
(
)
;
}
public
static
void
main
(
String
[
]
args
)
{
Set
<Integer>
set
=
Set
.
of
(
)
;
System
.
out
.
println
(
isNotEmpty
(
set
)
?
"Non-empty"
:
"Empty"
)
;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
import
org
.
apache
.
commons
.
collections4
.
CollectionUtils
;
import
java
.
util
.
Set
;
public
class
Main
{
public
static
void
main
(
String
[
]
args
)
{
Set
<Integer>
set
=
Set
.
of
(
)
;
System
.
out
.
println
(
CollectionUtils
.
isEmpty
(
set
)
?
"Empty"
:
"Non-empty"
)
;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
import
org
.
apache
.
commons
.
lang3
.
ObjectUtils
;
import
java
.
util
.
List
;
public
class
Main
{
public
static
void
main
(
String
[
]
args
)
{
List
<Integer>
set
=
List
.
of
(
)
;
System
.
out
.
println
(
ObjectUtils
.
isEmpty
(
set
)
?
"Empty"
:
"Non-empty"
)
;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
public
static
boolean
isEmpty
(
Object
object
)
{
if
(
object
==
null
)
{
return
true
;
}
else
if
(
object
instanceof
CharSequence
)
{
return
(
(
CharSequence
)
object
)
.
length
(
)
==
0
;
}
else
if
(
object
.
getClass
(
)
.
isArray
(
)
)
{
return
Array
.
getLength
(
object
)
==
0
;
}
else
if
(
object
instanceof
Collection
)
{
return
(
(
Collection
)
object
)
.
isEmpty
(
)
;
}
else
{
return
object
instanceof
Map
?
(
(
Map
)
object
)
.
isEmpty
(
)
:
false
;
}
}