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);
How to check if the lists that exist in myList have the same length? I know that I can check the length of each list by something like myList.get(0).size(), so what is an efficient and short way to check if all these lists have the same length (instead of checking one by one)?
You could use Stream.allMatch() by matching any contained list size (for example the first one) with all other contained lists :
boolean isSameLength =
myList.stream()
.allMatch(l -> l.size() == myList.get(0).size())
It makes the first comparison helpless as it compares the same contained list but it is more readable that :
boolean isSameLength =
myList.stream()
.skip(1)
.allMatch(l -> l.size() == myList.get(0).size())
You cannot hope to say that n lists have the same length without visiting them. You have to go one-by-one. davidxxx's answer shows a really nice way with streams but visits all the lists anyway. The naive way may be
public static boolean sameLength(List<List> lists){
if(lists.get(0) == null){ //EDIT: as davidxxx pointed out this if is superfluous
return true;
}
int len = lists.get(0).size();
for (List list : lists) {
if(list.size() != len){
return false;
}
}
return true;
}
My IDE even suggests using functional operators with the above code like davidxxx said.
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