
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Iterate Through ArrayList in Java
The iterator can be used to iterate through the ArrayList wherein the iterator is the implementation of the Iterator interface. Some of the important methods declared by the Iterator interface are hasNext() and next().
The hasNext() method returns true if there are more elements in the ArrayList and otherwise returns false. The next() method returns the next element in the ArrayList.
A program that demonstrates iteration through ArrayList using the Iterator interface is given as follows
Example
import java.util.ArrayList; import java.util.Iterator; import java.util.List; public class Demo { public static void main(String[] args) { List<String> aList = new ArrayList<String>(); aList.add("Adam"); aList.add("John"); aList.add("Nancy"); aList.add("Peter"); aList.add("Mary"); Iterator i = aList.iterator(); System.out.println("The ArrayList elements are:"); while (i.hasNext()) { System.out.println(i.next()); } } }
Output
The output of the above program is as follows
The ArrayList elements are: Adam John Nancy Peter Mary
Now let us understand the above program.
The ArrayList aList is created. Then ArrayList.add() is used to add the elements to this ArrayList. Then the ArrayList elements are displayed using the Iterator interface. A code snippet which demonstrates this is as follows
List<String> aList = new ArrayList<String>(); aList.add("Adam"); aList.add("John"); aList.add("Nancy"); aList.add("Peter"); aList.add("Mary"); Iterator i = aList.iterator(); System.out.println("The ArrayList elements are:"); while (i.hasNext()) { System.out.println(i.next()); }