How to use Iterator in Java

By Fazal Viewed: 19046 times Emailed: 171 times Printed: 241 times Bookmark and Share



Before you can access a collection through an iterator, you must obtain one. Each of the collection classes provides an iterator( ) method that returns an iterator to the start of the collection. By using this iterator object, you can access each element in the collection, one element at a time. In general, to use an iterator to cycle through the contents of a collection, follow these steps:

  1. Obtain an iterator to the start of the collection by calling the collection's iterator( )
  2. Set up a loop that makes a call to hasNext( ). Have the loop iterate as long as hasNext( ) returns true.
  3. Within the loop, obtain each element by calling next( ).

For collections that implement List, you can also obtain an iterator by calling ListIterator. As explained, a list iterator gives you the ability to access the collection in either the forward or backward direction and lets you modify an element. Otherwise, ListIterator is used just like Iterator.

Here is an example that implements these steps, demonstrating both Iterator and ListIterator. It uses an ArrayList object, but the general principles apply to any type of collection. Of course, ListIterator is available only to those collections that implement the List interface.

// Demonstrate iterators. 
import java.util.*; 
class IteratorDemo { 
public static void main(String args[]) { 
// create an array list 
ArrayList al = new ArrayList(); 
// add elements to the array list 
al.add("C"); 
al.add("A"); 
al.add("E"); 
al.add("B"); 
al.add("D"); 
al.add("F"); 
// use iterator to display contents of al 
System.out.print("Original contents of al: "); 
Iterator itr = al.iterator(); 
while(itr.hasNext()) {

    Object element = itr.next(); 
    System.out.print(element + " ");


System.out.println(); 
// modify objects being iterated 
ListIterator litr = al.listIterator(); 
while(litr.hasNext()) {

    Object element = litr.next(); 
    litr.set(element + "+");


System.out.print("Modified contents of al: "); 
itr = al.iterator();
while(itr.hasNext()) {

    Object element = itr.next(); 
    System.out.print(element + " ");


System.out.println(); 
// now, display the list backwards 
System.out.print("Modified list backwards: "); 
while(litr.hasPrevious()) {

    Object element = litr.previous(); 
    System.out.print(element + " ");


System.out.println(); 

}

The output is shown here: 

Original contents of al: C A E B D F 
Modified contents of al: C+ A+ E+ B+ D+ F+ 
Modified list backwards: F+ D+ B+ E+ A+ C+

Pay special attention to how the list is displayed in reverse. After the list is modified, litr points to the end of the list. (Remember, litr.hasNext( ) returns false when the end of the list has been reached.) To traverse the list in reverse, the program continues to use litr, but this time it checks to see whether it




Comments(23)


1. very good for programing

By: kiran at 2007-12-06 00:39:47
2. good

By: sasikiran at 2008-03-30 23:33:24
3. good quick explanation. Thanks

By: kay at 2008-12-08 21:10:13
4. Timely info right when I needed it. Thanks.

By: Electric Vehicles at 2008-12-10 15:15:25
5. Good explanation about Iterator. But Object declaration inside while loop is not all good style of programming.

By: Prasad at 2008-12-22 23:20:59
6. Thankyou it is Working Fine .....


By: PDCOE at 2009-02-11 23:02:29
7. Great Work for JAVA Beginners

By: Sudhir Rajgure at 2009-03-01 02:40:00
8. good understandability code

By: Raja Mahendra Kumar at 2009-03-05 03:11:26
9. Thank for your clear explanation

By: htnga at 2009-04-05 18:43:25
10. u doing good

By: matsiko at 2009-04-14 08:05:00
11. tnx .



By: smokes at 2009-04-15 07:30:19
12. just what i needed to understand iterators, gj

By: oak at 2009-04-20 15:46:39
13. thats good

By: P.Kumar at 2009-08-02 10:48:48
14. Thanks, much appreciated!
Saved a great deal of trawling thru- the classes and interfaces in the java documentation

By: alan at 2009-08-14 01:35:01
15. I'm a beginner, and I was told it is a good practice to use:

List list = new ArrayList();

I mean, to put the interface "List" to the left of '=', and not the implementation "ArrayList".

Thanks for letting me learn how to traverse the collection backwards!!!

By: Nelson at 2009-08-17 09:13:28
16. tnx, nice code...

By: Hansoc at 2009-08-18 00:17:58
17. could u pls tell me whcih class is implemted by iterator interface...
if any class implements then why not override the hasnext() ,next() and remove() method of iterator....how iterator reference variables are using these method without implementation


By: AMIT at 2009-10-04 00:21:30
18. The iterator returned by iterator() does not point to start of of collection. It points to head which is like -1.

By: Jeffrey at 2009-10-06 21:45:41
19. sir ji,
i want do learn for loop in java and form which i want to create different shapes like circle ellips trangle and rectangles

By: Prabhakar at 2009-11-06 00:48:53
20. i know this example this is in mg.hill but i want to know that with out set by ListIterator cant we print the value

By: srikanta at 2009-11-18 00:06:57
21. thks for help...

By: Peps at 2010-01-05 02:28:52
22. thks for help...

By: Peps at 2010-01-05 02:34:15
23. its realy gud which clears minor douts regarding the problems we are facing

By: Shripad at 2010-01-19 05:40:41

Your name (required):


Your email(required, will not be shown to the public):


Your sites URL (optional):


Your comments:


Enter Code:
The Captcha image

Latest Tutorials

[2010-01-01]Converting properties using PropertyEditors and Other Spring features worth mentioning
[2010-01-01]How to create an array and method in JSP
[2010-01-01]inheritance in Java
[2010-01-01]Use List, Set, SortedSet, LinkedHashSet, Map, LinkedHashMap in java
[2010-01-01]cloneable in Java
[2010-01-01]Java program for Associate keys with values
[2010-01-01]Java code for Enumeration and using java.lang.reflect.Array
[2010-01-01]Insert an element in Array, Search and Sort Array by using java program
[2010-01-01]Type Casting in Java
[2010-01-01]How to initialize an Array and how to copy the array
[2009-10-15]TCP Server and TCP Client in Java
[2009-10-03]Simple java program to add an element to specified index of Java ArrayList
[2009-10-03]How to use set, get basic and nested properties for Spring framework
[2009-10-03]How to access instance from an inner class and accessing outer class variables in java
[2009-10-03]How to use and access the inner class in java

More Latest News


Most Viewed Articles (in last 30 days)
How to use ArrayList in Java
How to Send SMS using Java Program (full code sample included)
How to use Iterator in Java
XML and Java - Parsing XML using Java Tutorial
Using substring( ) in Java
FileReader and FileWriter example program in Java
indexOf( ) and lastIndexOf( ) in Java
wait(), notify() and notifyAll() in Java - A tutorial
HashMap example in Java
compareTo( ) in Java
Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/commons/logging/LogFactory
Using StringTokenizer in Java
Transient vs Volatile modifiers in Java
Method Overloading (function overloading) in Java
instanceof sample program in Java
Most Emailed Articles (in last 30 days)
Components of program
How to Send SMS using Java Program (full code sample included)
XML and Java - Parsing XML using Java Tutorial
Execute system commands in a Java Program
Why java is important to the Internet
indexOf( ) and lastIndexOf( ) in Java
History of Object
FileReader and FileWriter example program in Java
Recursion in java
What is Java?
Sample Java Script that displays a movable clock
Overview of JavaScript Objects
compareTo( ) in Java
How to use ArrayList in Java
Executing Java Scripts