I have a list of lists in Java. Here is the code:
List<List<Integer>> myList = new ArrayList<>();
myList.add(new ArrayList<Integer>());
myList.add(new ArrayList<Integer>());
myList.add(new ArrayList<Integer>());
myList.get(0).add(1);
myList.get(0).add(2);
myList.get(0).add(3);
myList.get(1).add(4);
myList.get(1).add(5);
myList.get(1).add(6);
myList.get(2).add(7);
myList.get(2).add(8);
myList.get(2).add(9);
Now in a part of my code I want to check if all three lists that are located in myList
are not empty and null. Should I check each of these lists one by one, like this:
if (myList.get(0) != null && !myList.get(0).isEmpty()) {
// do something
}
...or is there a better and shorter way to do instead of checking one by one?
Use the any() function. This returns True if any list within the list is not empty.
Using len() With Comparison Operator In the code above, len(py_list) == 0 will be true if the list is empty and will will be redirected to the else block.
Use the all() function to check if all items in a list are None in Python, e.g. if all(i is None for i in my_list): . The all() function takes an iterable as an argument and returns True if all of the elements in the iterable are truthy (or the iterable is empty).
Check if a list is empty using 'not' operator in python. In python, a sequence object can be implicitly convertible to bool. If the sequence is empty, then it evaluates to False else it evaluates to True. So, we can apply an if statement to a sequence object to check if it is empty or not.
You can use stream API for this, but also a plain loop too:
boolean allNonEmptyOrNull = myList.stream()
.allMatch(x -> x != null && !x.isEmpty());
Or you can check if null
is contained or an an empty List
for example, via:
System.out.println(myList.contains(null) || myList.contains(Collections.<Integer> emptyList()));
But this last option will break with Java 9 immutable collections, for example:
List.of(1, 2, 3).contains(null);
will throw a NullPointerException
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With