CollectionUtils class of Apache Commons Collections library provides various utility methods for common operations covering wide range of use cases. It helps avoid writing boilerplate code. This library is very useful prior to jdk 8 as similar functionalities are now provided in Java 8's Stream API.
isNotEmpty() method of CollectionUtils can be used to check if a list is not empty without worrying about null list. So null check is not required to be placed everywhere before checking the size of the list.
Following is the declaration for
org.apache.commons.collections4.CollectionUtils.isNotEmpty() method −
public static boolean isNotEmpty(Collection<?> coll)
coll − The collection to check, may be null.
True if non-null and non-empty.
The following example shows the usage of org.apache.commons.collections4.CollectionUtils.isNotEmpty() method. We'll check a list is empty or not.
import java.util.List; import org.apache.commons.collections4.CollectionUtils; public class CollectionUtilsTester { public static void main(String[] args) { List<String> list = getList(); System.out.println("Non-Empty List Check: " + checkNotEmpty1(list)); System.out.println("Non-Empty List Check: " + checkNotEmpty1(list)); } static List<String> getList() { return null; } static boolean checkNotEmpty1(List<String> list) { return !(list == null || list.isEmpty()); } static boolean checkNotEmpty2(List<String> list) { return CollectionUtils.isNotEmpty(list); } }
The output is given below −
Non-Empty List Check: false Non-Empty List Check: false
isEmpty() method of CollectionUtils can be used to check if a list is empty without worrying about null list. So null check is not required to be placed everywhere before checking the size of the list.
Following is the declaration for
org.apache.commons.collections4.CollectionUtils.isEmpty() method −
public static boolean isEmpty(Collection<?> coll)
coll − The collection to check, may be null.
True if empty or null.
The following example shows the usage of org.apache.commons.collections4.CollectionUtils.isEmpty() method. We'll check a list is empty or not.
import java.util.List; import org.apache.commons.collections4.CollectionUtils; public class CollectionUtilsTester { public static void main(String[] args) { List<String> list = getList(); System.out.println("Empty List Check: " + checkEmpty1(list)); System.out.println("Empty List Check: " + checkEmpty1(list)); } static List<String> getList() { return null; } static boolean checkEmpty1(List<String> list) { return (list == null || list.isEmpty()); } static boolean checkEmpty2(List<String> list) { return CollectionUtils.isEmpty(list); } }
Given below is the output of the code −
Empty List Check: true Empty List Check: true