I have a break for 5 minutes and want to find as more as possible ways to check that list is empty in Java. Just for fun, there is no sense in this article.
Suppose, at some point of code we receive variable list
of type List<Integer>
and we need to sum all numbers only if
list is not empty. What is the most elegant way to check that list is not empty?
Defensive approach, null-safety first:
if (list != null) {
// list is not null
}
List is not null, but it does not guarantee that list is not empty. Let’s iterate:
if (list != null && list.size() != 0)) {
// ...
}
List
has method isEmpty
and for ArrayList
, as example, it is identical:
/**
* Returns {@code true} if this list contains no elements.
*
* @return {@code true} if this list contains no elements
*/
public boolean isEmpty() {
return size == 0;
}
Let’s improve readability:
if (list != null && !list.isEmpty()) {
// ...
}
More variants? Let’s use Optional:
if (Optional.ofNullable(list).map(List::isEmpty).orElse(false)) {
// ...
}
Could you propose additional examples, just for fun?