In this tutorial, we will see 5 different ways to iterate ArrayList in java.

Iterate ArrayList in Java :

Create ArrayList :

ArrayList<String> fruitsList = new ArrayList(); 
fruitsList.add("Banana"); 
fruitsList.add("Apple"); 
fruitsList.add("Grapes"); 
fruitsList.add("Mango");

I am going to iterate the above ArrayList in 5 different ways.

Method 1 : Ierating using for loop

for(int i=0;i<fruitsList.size();i++){
       System.out.println(fruitsList.get(i));
}

Method 2 : Iterate using while loop

int i = 0;
while(fruitsList.size() > i){
     System.out.println(fruitsList.get(i));
     i++;
}

Method 3 : Iterate using advanced for loop

for (String fruit: fruitsList ) {
      System.out.println(fruit);
}

Method 4 : Iterate using java.util.Iterator class

Iterator it = fruitsList.iterator();
while (it.hasNext()) {
     System.out.println(it.next());
}

Method 5 : Iterate using Java 8 Stream API

you can see the more information about Java 8 Stream with ArrayList

fruitsList.forEach((fruit)->System.out.println(fruit));

Output :

The above 5 ways of iterators gives same output like below.

Banana
Apple
Grapes
Mango

Reference :

Java8 forEach Example

Happy Learning 🙂

Leave A Comment