Iterate through an ArrayList of ArrayLists in Java

Viewed 16174

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

          } }
5 Answers

Old question, but I am just curious why no one has mentioned this way,

for(int i=0; i<list.size(); i++) {          
    for(int j=0; j<list.get(i).size(); j++) {
        System.out.print(list.get(i).get(j) + " ");    
    }
    System.out.println();
}

This is same as accessing a matrix in 2D arrays.

Here some functional approach:

    ArrayList<ArrayList<Integer>> row1 = new ArrayList<>();
    row1.add(new ArrayList<>(Arrays.asList(1, 2, 3)));
    row1.add(new ArrayList<>(Arrays.asList(4, 5, 6)));
    row1.stream().flatMap(Collection::stream).forEach(System.out::println);
Related