

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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()); }
- Related Questions & Answers
- 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?
- Loop through the Vector elements using an Iterator in Java
- How to iterate List using Iterator in Java?
- Iterator vs Collection in Java
- Iterate through ArrayList in Java
- Iterate through elements of a LinkedList using a ListIterator in Java
- Iterate through Java Unit Tuple
- Iterate through Java Pair Tuple
- Use Iterator to remove an element from a Collection in Java
- Iterate through Decade Tuple in Java
- Iterate through Ennead Tuple in Java
Advertisements