8

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

          } }
0

5 Answers 5

5

This is the canonical way you do it:

for(List<Integer> innerList : row1) {
    for(Integer number : innerList) {
        System.out.println(number);
    }
}
Sign up to request clarification or add additional context in comments.

Comments

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

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

Comments

0

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

Comments

0

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

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.