How check if the lists in a list are not empty

0
23
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 list are not empty. Should I check each of these lists one by one like if (list .get(0) != null && !list .get(0).isEmpty()) { do something } or is there a better and shorter way to do instead of checking one by one?

use stream api for this, but also a plain loop too:

 boolean allNonEmptyOrNull = L.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(L.contains(null) || L.contains(Collections.<Integer> emptyList()));

 

if (!L.contains(Collections.EMPTY_LIST)){ do something }

 

LEAVE A REPLY

Please enter your comment!
Please enter your name here