List is null or empty Java

This post will discuss different ways to check whether a list is empty in Java. A list is empty if and only if it contains no elements.

1. Using List.isEmpty[] method

The recommended approach is to use the List.isEmpty[] method to check for an empty list in Java. Following is a simple example demonstrating usage of this method:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import java.util.ArrayList;
import java.util.List;
class Main {
public static void main[String[] args] {
List list = new ArrayList[];
if [list == null] {
System.out.println["List is null"];
}
if [list.isEmpty[]] {
System.out.println["List is empty"];
}
else {
System.out.println["List is not empty or null"];
}
}
}


Instead of explicitly checking if the list is null or empty, you can combine the isEmpty[] method with a null check in a single expression, as shown below:

1
2
3
4
5
6
7
8
9
10
11
12
import java.util.Arrays;
import java.util.List;
class Main {
public static void main[String[] args] {
List list = Arrays.asList[1, 2, 3];
if [list == null || list.isEmpty[]] {
System.out.println["List is empty or null"];
}
}
}


Or, even better:

1
2
3
4
5
6
7
8
9
10
11
12
import java.util.Arrays;
import java.util.List;
class Main {
public static void main[String[] args] {
List list = Arrays.asList[1, 2, 3];
if [list != null && !list.isEmpty[]] {
System.out.println["List is not empty"];
}
}
}

2. Using List.size[] method

Finally, you can use the List.size[] method, which returns the total number of items in it.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import java.util.Arrays;
import java.util.List;
class Main {
public static void main[String[] args] {
List list = Arrays.asList[1, 2, 3];
if [list != null && list.size[] > 0] {
System.out.println["List is not empty"];
} else {
System.out.println["List is empty or null"];
}
}
}

Thats all about checking whether a list is empty in Java.

Video liên quan

Chủ Đề