helen :
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?
Eugene :
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
.