The method of judging whether the List and Map collections are empty

In Java, there are several ways to determine whether a collection is empty. Here are some of them:

1. Use the List.isEmpty() method. For example: 

List<String> list = new ArrayList<>();
if (list.isEmpty()) {
    System.out.println("List is empty.");
}

The List collection here is equivalent to a bottle, and there is no water yet. 

List<String> list = null;
if (list.isEmpty()) {
    System.out.println("List is empty.");
}

 The List collection here has not been initialized, which means that the bottle does not exist yet. Using list.isEmpty() will generate a NullPointerException. 

List<String> list = null;
if (CollUtil.isNotEmpty(list )) {
    System.out.println("List is empty.");
}

So usually use list != null && list.size > 0 to judge, or directly use isEmpty of the CollUtil tool in HuTool. There are also Set, Map, etc.

2. Use the List. size() method. For example:

List<String> list = new ArrayList<>();
if (list.size() == 0) {
    System.out.println("List is empty.");
}

3. Use the CollectionUtils.isNotEmpty(Collection coll) method. This requires the use of the Apache Commons Collections library. For example:

List<String> list = new ArrayList<>();
if (CollectionUtils.isNotEmpty(list)) {
    System.out.println("List is not empty.");
}

In Java, there are several ways to determine whether the Map collection is empty. Here are some of them:

1. Use the Map.isEmpty() method. For example:

Map<String, String> map = new HashMap<>();
if (map.isEmpty()) {
    System.out.println("Map is empty.");
}


2. Use the Map. size() method. For example:

Map<String, String> map = new HashMap<>();
if (map.size() == 0) {
    System.out.println("Map is empty.");
}

If you have anything else, welcome to add! ! !

Guess you like

Origin blog.csdn.net/ssghzxc/article/details/130269263