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

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

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

davidxxx :

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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=111001&siteId=1