How to use Iterator in Java

By Fazal Viewed: 33059 times Emailed: 284 times Printed: 413 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(24)


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
24. Good information...it help me to do mi projecto! thanks.

By: gnk at 2010-08-12 01:01:50

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-09-02]Steps in using verisign certificate with Glassfish appserver
[2010-08-02]emulator 0 terminated while waiting for it to register!
[2010-08-02]Cannot run program "C:\Program Files\Java\jre6\bin\javac.exe": CreateProcess error=2, The system cannot find the file specified
[2010-08-01]Step by Step guide to setup freetts for Java
[2010-07-31]Speech Packages available for Java API
[2010-07-31]Tutorial on setting up freetts with maven
[2010-07-31]package com.sun.speech.freetts does not exist.
[2010-07-31]Text to Speech conversion program in Java
[2010-07-31]How to create wav file using freetts
[2010-07-31]How to set the width of a Text element in JavaFX?
[2010-07-31]Major components of FxObjects in JavaFX
[2010-07-03]Using the AWS SDK for Java in Eclipse
[2010-07-03]Using the AWS SDK for Java
[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

More Latest News

Most Viewed Articles (in last 30 days)
How to use ArrayList in Java
XML and Java - Parsing XML using Java Tutorial
How to use Iterator in Java
How to Send SMS using Java Program (full code sample included)
Using substring( ) in Java
indexOf( ) and lastIndexOf( ) in Java
FileReader and FileWriter example program in Java
Using StringTokenizer in Java
HashMap example in Java
wait(), notify() and notifyAll() in Java - A tutorial
Method Overloading (function overloading) in Java
Abstract classes in Java
Method Overriding in Java
Transient vs Volatile modifiers in Java
compareTo( ) 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
Why java is important to the Internet
How to use ArrayList in Java
Execute system commands in a Java Program
FileReader and FileWriter example program in Java
Recursion in java
indexOf( ) and lastIndexOf( ) in Java
What is Java?
Method Overloading (function overloading) in Java
Sample Java Script that displays a movable clock
compareTo( ) in Java
History of Object
How to use Iterator in Java