- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- 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 a Collection using an Iterator in Java
A collection in Java provides an architecture to handle a group of objects. The different classes in the Java Collection Framework are ArrayList, LinkedList, HashSet, Vector etc.
An Iterator can be used to iterate through a Collection and a program that demonstrates this using ArrayList 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("John"); aList.add("Peter"); aList.add("Harry"); aList.add("James"); aList.add("Arthur"); System.out.println("The ArrayList elements are: "); for (Iterator i = aList.iterator(); i.hasNext();) { System.out.println(i.next()); } } }
Output
The ArrayList elements are: John Peter Harry James Arthur
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("John"); aList.add("Peter"); aList.add("Harry"); aList.add("James"); aList.add("Arthur"); System.out.println("The ArrayList elements are: "); for (Iterator i = aList.iterator(); i.hasNext();) { System.out.println(i.next()); }
- Related Articles
- Iterate through a LinkedList using an Iterator in Java
- Loop through a HashMap using an Iterator in Java
- Loop through an ArrayList using an Iterator in Java
- Iterate through an ArrayList using a ListIterator in Java
- How to iterate a Java List using Iterator?
- How to iterate List using Iterator in Java?
- Loop through the Vector elements using an Iterator in Java
- Iterator vs Collection in Java
- Use Iterator to remove an element from a Collection in Java
- How an iterator object can be used to iterate a list in Java?
- Iterate through elements of a LinkedList using a ListIterator in Java
- Retrieving Elements from Collection in Java- Iterator
- Iterate through ArrayList in Java
- Iterate through a LinkedList in reverse direction using a ListIterator in Java
- How to iterate the contents of a collection using forEach() in Java?

Advertisements