A Developer Gateway To IT World...

Techie Uncle Software Testing Core Java Java Spring C Programming Operating System HTML 5 Java 8 ES6 Project

How to iterate ArrayList element in java?

Java provides util package, in which Iterator is class that is used to iterate list element. So that we have to import java.util.Iterator;

Iterator in Java
Returns an iterator over the elements in this list in proper sequence.
The returned iterator is fail-fast.

Specified by: iterator() in List, Overrides: iterator() in AbstractList


import java.util.ArrayList;
import java.util.Iterator;

public class TestArrayListClass {

       public static void main(String[] args) {
            
             //create arrayList
             ArrayList aList = new ArrayList();
            
             //add elements in list
             aList.add(10);
             aList.add("programming");
             aList.add(123);
             aList.add("shifts");
            
             //how to iterate ArrayList
            
             Iterator  itr = aList.iterator();
             while(itr.hasNext())
             {
                 System.out.println(itr.next()); 
             }
       } 
}



Output:

10
programming
123
shifts

LEARN TUTORIALS

.

.