Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate through an ArrayList of ArrayLists in Java

I have the following ArrayList...

ArrayList<ArrayList<Integer>> row1 = new ArrayList<ArrayList<Integer>>();

The following arraylists are added to it....

row1.add(cell1);
row1.add(cell2);
row1.add(cell3);
row1.add(cell4);
row1.add(totalStockCell);

I want to iterate through the arraylist row1 and print the contents.

Would a loop within a loop work here?

E.g.

while(it.hasNext()) {

//loop on entire list of arraylists
    while(it2.hasNext) {
      //each cell print values in list

          } }
like image 899
user2863323 Avatar asked Dec 09 '13 12:12

user2863323


2 Answers

This is the canonical way you do it:

for(List<Integer> innerList : row1) {
    for(Integer number : innerList) {
        System.out.println(number);
    }
}
like image 132
Adam Arold Avatar answered Oct 22 '22 18:10

Adam Arold


for (ArrayList<Integer> list : row1)
{
    for (Integer num : list)
    {
        //doSomething
    }
}

Java enhanced-for loops use an iterator behind the scenes.

like image 25
Steve P. Avatar answered Oct 22 '22 19:10

Steve P.