Iterate through ArrayList from 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 over the string arraylist1 and print the contents.

Will loop in loop work here?

eg.

while(it.hasNext()) {

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

          } }
+7
source share
5 answers

This is the canonical way you do this:

for(List<Integer> innerList : row1) {
    for(Integer number : innerList) {
        System.out.println(number);
    }
}
+4
source
for (ArrayList<Integer> list : row1)
{
    for (Integer num : list)
    {
        //doSomething
    }
}

An advanced Java loop uses an iterator behind the scenes.

+2
source

Iterator, :

    Iterator<ArrayList<Integer>> it = row1.iterator();

    while(it1.hasNext())
        {
        Iterator<Integer> itr = it.next().iterator();
        while(itr.hasNext())
            {
            System.out.println(itr.next());
            }
        }
0

, , ,

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

, .

0

:

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

All Articles