1

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?

1
  • 1
    1] your code should be iterating over each entry of the top-level list, so I'm not quite sure how you're not getting both "rows" (check your output again). 2] list4 is a terrible name for a variable, try to find something more descriptive. 3] If possible, you should be de-serializing what is obviously some form of data into a better object. For one thing, it would help to make your dates unambiguous. Commented Jan 22, 2016 at 7:13

2 Answers 2

8

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);
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

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

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.