How check if the lists in a list are not empty

  • A+

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 (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?


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

 boolean allNonEmptyOrNull =      .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


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: