Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How check if the lists in a list are not empty?

Tags:

java

list

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?

like image 696
helen Avatar asked Oct 11 '18 20:10

helen


People also ask

How do you check if a list inside a list is empty?

Use the any() function. This returns True if any list within the list is not empty.

How do you know if a list is non 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.

How do you check if all values in a list are empty Python?

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).

How do I check if an element is not empty in Python?

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.


1 Answers

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.

like image 86
Eugene Avatar answered Oct 18 '22 07:10

Eugene