简体   繁体   中英

How to iterate arraylist of arrayLists

I Have a list which is in

[
    [SAM, 12/01/2015, 9A-6P], 
    [JAM, 12/02/2015, 9A-6P]
]

I need to iterate it.I tried the below code

for (int i = 0; i < list4.size(); i++) {
            System.out.println("List" + list4.get(i).toString());
}
//this is giving me [SAM, 12/01/2015, 9A-6P]

but I want to iterate the above one also [SAM, 12/01/2015, 9A-6P] .

Can anybody have idea?

You can and should use the fact that every List is also an Iterable . So you can use this:

// Idk what you list actually contains
// So I just use Object
List<List<Object>> listOfLists; 
for(List<Object> aList : listOfLists) {
    for(Object object : aList) {
        // Do whatever you want with the object, e.g.
        System.out.println(object);
    }
}

Tried your case with below example. Hope it helps

import java.util.ArrayList;
import java.util.List;

public class IterateList {
  public static void main(String[] args) {
    List<List<String>> myList = new ArrayList<List<String>>();

    List<String> list1 = new ArrayList<String>();
    list1.add("SAM");
    list1.add("12/01/2015");
    list1.add("9A-6P");

    List<String> list2 = new ArrayList<String>();
    list2.add("JAM");
    list2.add("12/01/2015");
    list2.add("9A-6P");

    myList.add(list1);
    myList.add(list2);

    for (List list : myList) {
      for(int i=0; i<list.size();i++){
        System.out.println(list.get(i));
      }

    }
  }
}

Output:
SAM
12/01/2015
9A-6P
JAM
12/01/2015
9A-6P

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