2

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...?

2
  • Loops can be nested. Give it a try and write some code. Commented Feb 8, 2013 at 6:25
  • Use Lambdaj or Guava for their awesomeness Commented Feb 8, 2013 at 7:30

3 Answers 3

3

Try something like this .

for( Plant plant : plants) {
    for(Flowers flower : plant.getFlowers()) {
        System.out.println(flower.getName());
    } 
}
Sign up to request clarification or add additional context in comments.

Comments

0
    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.
        }
    }

Comments

0

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));
    }
    }
    }

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.