
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 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()); }
Advertisements