[java] How to iterate through an ArrayList of Objects of ArrayList of Objects?

Using an example:

Let say I have a class call Gun. I have another class call Bullet.

Class Gun has an ArrayList of Bullet.

To iterate through the Arraylist of Gun ..instead of doing this:

ArrayList<Gun> gunList = new ArrayList<Gun>();
for (int x=0; x<gunList.size(); x++)
    System.out.println(gunList.get(x));

We can simply iterate through the ArrayList of Gun as such:

for (Gun g: gunList) System.out.println(g); 

Now, I want to iterate and print out all Bullet of my 3rd Gun object:

for (int x=0; x<gunList.get(2).getBullet().size(); x++)  //getBullet is just an accessor method to return the arrayList of Bullet 
    System.out.println(gunList.get(2).getBullet().get(x));

Now my question is: Instead of using the conventional for-loop, how do I printout the list of gun objects using the ArrayList iteration ?

This question is related to java object arraylist iteration

The answer is


You want to follow the same pattern as before:

for (Type curInstance: CollectionOf<Type>) {
  // use currInstance
}

In this case it would be:

for (Bullet bullet : gunList.get(2).getBullet()) {
   System.out.println(bullet);
}

When using Java8 it would be more easier and a single liner only.

    gunList.get(2).getBullets().forEach(n -> System.out.println(n));

Edit:

Well, he edited his post.

If an Object inherits Iterable, you are given the ability to use the for-each loop as such:

for(Object object : objectListVar) {
     //code here
}

So in your case, if you wanted to update your Guns and their Bullets:

for(Gun g : guns) {
     //invoke any methods of each gun
     ArrayList<Bullet> bullets = g.getBullets()
     for(Bullet b : bullets) {
          System.out.println("X: " + b.getX() + ", Y: " + b.getY());
          //update, check for collisions, etc
     }
}

First get your third Gun object:

Gun g = gunList.get(2);

Then iterate over the third gun's bullets:

ArrayList<Bullet> bullets = g.getBullets();

for(Bullet b : bullets) {
     //necessary code here
}

int i = 0; // Counter used to determine when you're at the 3rd gun
for (Gun g : gunList) { // For each gun in your list
    System.out.println(g); // Print out the gun
    if (i == 2) { // If you're at the third gun
        ArrayList<Bullet> bullets = g.getBullet(); // Get the list of bullets in the gun
        for (Bullet b : bullets) { // Then print every bullet
            System.out.println(b);
        }
    i++; // Don't forget to increment your counter so you know you're at the next gun
}

for (Bullet bullet : gunList.get(2).getBullet()) System.out.println(bullet);

We can do a nested loop to visit all the elements of elements in your list:

 for (Gun g: gunList) {
   System.out.print(g.toString() + "\n   "); 
   for(Bullet b : g.getBullet() {
      System.out.print(g);    
   }
   System.out.println(); 
 }

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to object

How to update an "array of objects" with Firestore? how to remove json object key and value.? Cast object to interface in TypeScript Angular 4 default radio button checked by default How to use Object.values with typescript? How to map an array of objects in React How to group an array of objects by key push object into array Add property to an array of objects access key and value of object using *ngFor

Examples related to arraylist

Adding null values to arraylist How to iterate through an ArrayList of Objects of ArrayList of Objects? Dynamically adding elements to ArrayList in Groovy How to replace existing value of ArrayList element in Java How to remove the last element added into the List? How to append elements at the end of ArrayList in Java? Removing Duplicate Values from ArrayList How to declare an ArrayList with values? In Java, can you modify a List while iterating through it? Load arrayList data into JTable

Examples related to iteration

Is there a way in Pandas to use previous row value in dataframe.apply when previous value is also calculated in the apply? How to loop over grouped Pandas dataframe? How to iterate through a list of dictionaries in Jinja template? How to iterate through an ArrayList of Objects of ArrayList of Objects? Ways to iterate over a list in Java Python list iterator behavior and next(iterator) How to loop through an array containing objects and access their properties recursion versus iteration What is the perfect counterpart in Python for "while not EOF" How to iterate over a JavaScript object?