简体   繁体   中英

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?

Eg

while(it.hasNext()) {

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

          } }

This is the canonical way you do it:

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

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

If you want to use Iterator, nested loops will work:

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM