Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to check if the lists in a list have the same length

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

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

like image 681
helen Avatar asked Jan 29 '26 13:01

helen


2 Answers

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())
like image 198
davidxxx Avatar answered Jan 31 '26 03:01

davidxxx


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.

like image 38
Raven221221221 Avatar answered Jan 31 '26 02:01

Raven221221221



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!