Loop Through an ArrayList Using an Iterator in Java
An Iterator can be used to loop through an ArrayList. The method hasNext( ) returns true if there are more elements in ArrayList and false otherwise. The method next( ) returns the next element in the ArrayList and throws the exception NoSuchElementException if there is no next element.
A program that demonstrates this is given as follows.
Example
import java.util.ArrayList; import java.util.Iterator; public class Demo { public static void main(String[] args) { ArrayList<String> aList = new ArrayList<String>(); aList.add("Apple"); aList.add("Mango"); aList.add("Guava"); aList.add("Orange"); aList.add("Peach"); System.out.println("The ArrayList elements are: "); for (Iterator iter = aList.iterator(); iter.hasNext();) { System.out.println(iter.next()); } } }
Output
The output of the above program is as follows −
The ArrayList elements are: Apple Mango Guava Orange Peach
Now let us understand the above program.
The ArrayList is created and ArrayList.add() is used to add the elements to the ArrayList. Then the ArrayList elements are displayed using an iterator which makes use of the Iterator interface. A code snippet which demonstrates this is as follows
ArrayList<String> aList = new ArrayList<String>(); aList.add("Apple"); aList.add("Mango"); aList.add("Guava"); aList.add("Orange"); aList.add("Peach"); System.out.println("The ArrayList elements are: "); for (Iterator iter = aList.iterator(); iter.hasNext();) { System.out.println(iter.next()); }
Advertisements