user1999158
user1999158

Reputation: 35

Java ArrayList concept

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

Answers (3)

uday
uday

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

vikiiii
vikiiii

Reputation: 9476

Try something like this .

for( Plant plant : plants) {
    for(Flowers flower : plant.getFlowers()) {
        System.out.println(flower.getName());
    } 
}

Upvotes: 3

Achintya Jha
Achintya Jha

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

Related Questions