简体   繁体   English

通过Java中的ArrayLists的ArrayList进行迭代

[英]Iterate through an ArrayList of ArrayLists in Java

I have the following ArrayList... 我有以下ArrayList ...

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

The following arraylists are added to it.... 添加了以下arraylists ....

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. 我想遍历arraylist row1并打印内容。

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. Java增强型for循环在后台使用迭代器。

If you want to use Iterator, nested loops will work: 如果要使用Iterator,嵌套循环将起作用:

    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. 这与访问2D阵列中的矩阵相同。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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