Reputation: 35
How do you loop through an ArrayList within an ArrayList?
For example, If I have an ArrayList called plants of Plant objects. And each Plant object has a random number of flowerNames inside. How do I go through the ArrayList, stop at each Plant and print out the Plant's list of flowerNames? (just an example) and then move on to the next Plant, etc.
Plant: has an ArrayList of Flowers: has an ArrayList of flowerNames
Plant is in one class, Flowers is in another class
Is there a way to do this with the standard for loop? Not interate...?
Upvotes: 2
Views: 495
Reputation: 359
if you are not sure at which position you will get another list object use instance of method and check. Sample code is here.
for(int i=0;i<l1.size();i++){
if(!(l1.get(i) instanceof List<?>)){
System.out.println(l1.get(i));
}
else {
for(int j=0;j<((List)l1.get(i)).size();j++){
System.out.println(((List)l1.get(i)).get(j));
}
}
}
Upvotes: 0
Reputation: 9476
Try something like this .
for( Plant plant : plants) {
for(Flowers flower : plant.getFlowers()) {
System.out.println(flower.getName());
}
}
Upvotes: 3
Reputation: 12843
ArrayList<Object> outerList = new ArrayList<Object>();
ArrayList<Object> innerList = new ArrayList<Object>();
for(Object outer: outerList){
for(Object inner: innerList){
//Perform operation with innerList. Print or something else.
}
}
Upvotes: 0