在 Java 中遍历 ArrayList 的 ArrayList
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20470705/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Iterate through an ArrayList of ArrayLists in Java
提问by user2863323
I have the following ArrayList...
我有以下 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.
我想遍历数组列表 row1 并打印内容。
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
} }
回答by Steve P.
for (ArrayList<Integer> list : row1)
{
for (Integer num : list)
{
//doSomething
}
}
Java enhanced-for loops use an iterator behind the scenes.
Java 增强 for 循环在幕后使用迭代器。
回答by Adam Arold
This is the canonical way you do it:
这是您执行此操作的规范方式:
for(List<Integer> innerList : row1) {
for(Integer number : innerList) {
System.out.println(number);
}
}
回答by Mehmet Sedat Güng?r
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());
}
}
回答by Tan-007
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.
这与访问二维数组中的矩阵相同。
回答by Ludov Dmitrii
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);