How to use Iterator in Java

By: Fazal Emailed: 1607 times Printed: 2075 times    

Latest comments
By: rohit kumar - how this program is work
By: Kirti - Hi..thx for the hadoop in
By: Spijker - I have altered the code a
By: ali mohammed - why we use the java in ne
By: ali mohammed - why we use the java in ne
By: mizhelle - when I exported the data
By: raul - no output as well, i'm ge
By: Rajesh - thanx very much...
By: Suindu De - Suppose we are executing

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


Java Home | All Java Tutorials | Latest Java Tutorials

Sponsored Links

If this tutorial doesn't answer your question, or you have a specific question, just ask an expert here. Post your question to get a direct answer.



Bookmark and Share

Comments(51)


1. View Comment

very good for programing

View Tutorial          By: kiran at 2007-12-06 00:39:47
2. View Comment

good

View Tutorial          By: sasikiran at 2008-03-30 23:33:24
3. View Comment

good quick explanation. Thanks

View Tutorial          By: kay at 2008-12-08 21:10:13
4. View Comment

Timely info right when I needed it. Thanks.

View Tutorial          By: Electric Vehicles at 2008-12-10 15:15:25
5. View Comment

Good explanation about Iterator. But Object declaration inside while loop is not all good style of programming.

View Tutorial          By: Prasad at 2008-12-22 23:20:59
6. View Comment

Thankyou it is Working Fine .....

View Tutorial          By: PDCOE at 2009-02-11 23:02:29
7. View Comment

Great Work for JAVA Beginners

View Tutorial          By: Sudhir Rajgure at 2009-03-01 02:40:00
8. View Comment

good understandability code

View Tutorial          By: Raja Mahendra Kumar at 2009-03-05 03:11:26
9. View Comment

Thank for your clear explanation

View Tutorial          By: htnga at 2009-04-05 18:43:25
10. View Comment

u doing good

View Tutorial          By: matsiko at 2009-04-14 08:05:00
11. View Comment

tnx .

View Tutorial          By: smokes at 2009-04-15 07:30:19
12. View Comment

just what i needed to understand iterators, gj

View Tutorial          By: oak at 2009-04-20 15:46:39
13. View Comment

thats good

View Tutorial          By: P.Kumar at 2009-08-02 10:48:48
14. View Comment

Thanks, much appreciated!
Saved a great deal of trawling thru- the classes and interfaces in the java documentation


View Tutorial          By: alan at 2009-08-14 01:35:01
15. View Comment

I'm a beginner, and I was told it is a good practice to use:

List <String>list = new ArrayList<String>();

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!!!


View Tutorial          By: Nelson at 2009-08-17 09:13:28
16. View Comment

tnx, nice code...

View Tutorial          By: Hansoc at 2009-08-18 00:17:58
17. View Comment

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


View Tutorial          By: AMIT at 2009-10-04 00:21:30
18. View Comment

The iterator returned by iterator() does not point to start of of collection. It points to head which is like -1.

View Tutorial          By: Jeffrey at 2009-10-06 21:45:41
19. View Comment

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


View Tutorial          By: Prabhakar at 2009-11-06 00:48:53
20. View Comment

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

View Tutorial          By: srikanta at 2009-11-18 00:06:57
21. View Comment

thks for help...

View Tutorial          By: Peps at 2010-01-05 02:28:52
22. View Comment

thks for help...

View Tutorial          By: Peps at 2010-01-05 02:34:15
23. View Comment

its realy gud which clears minor douts regarding the problems we are facing

View Tutorial          By: Shripad at 2010-01-19 05:40:41
24. View Comment

Good information...it help me to do mi projecto! thanks.

View Tutorial          By: gnk at 2010-08-12 01:01:50
25. View Comment

PROGRAMMING SUPERB

View Tutorial          By: vinay sharma at 2010-10-01 05:16:23
26. View Comment

Thanks for giving iterator example

View Tutorial          By: Rajesh Kumar at 2010-11-03 05:17:05
27. View Comment

superb...thanks :-)

View Tutorial          By: sunny at 2010-11-10 07:20:25
28. View Comment

Thanks for this article. Now I can understand Iterator better.

View Tutorial          By: Rajesh Kumar at 2010-12-14 03:27:25
29. View Comment

well example, but i have to send the received list from servlet to jsp , to servlet again

View Tutorial          By: amit kumar at 2011-02-21 00:43:15
30. View Comment

Great stuff, learned more from this example than reading java books on the same topic for hours.

View Tutorial          By: David Bandelin at 2011-03-22 07:10:38
31. View Comment

I am still going through the tutorial, but it seems to trail off or that last sentence is truncated.

What comes after...
".. but this time it checks to see whether it" ?


View Tutorial          By: shadowwraith at 2011-06-08 08:00:57
32. View Comment

extremely good

View Tutorial          By: rahul at 2011-06-09 05:59:43
33. View Comment

good and nice

View Tutorial          By: Elayaraja j at 2011-06-18 05:30:07
34. View Comment

Nice Example.Good work.keep it up.
Thanks,
-Lucky


View Tutorial          By: Lucky at 2011-07-08 10:36:38
35. View Comment

Also note that for reverse ordering, If you have a Collection that implements either Deque (like LinkedList) or SortedSet (like TreeSet), you can get a reverse iterator (in Java 6) with the descendingIterator() method.

View Tutorial          By: Dwight at 2011-07-13 22:13:45
36. View Comment

This is Nice start for programmer '
Thanks ..


View Tutorial          By: Sagar Ikhankar at 2011-07-22 06:12:44
37. View Comment

The sample code was all I needed to figure out how to use iterators. Thanks.

View Tutorial          By: David at 2011-08-28 07:34:28
38. View Comment

good explanation ,it is very very understandable

View Tutorial          By: chaitanya at 2011-10-27 16:21:55
39. View Comment

its really a good post... very informative..

View Tutorial          By: javagava at 2011-12-13 19:49:08
40. View Comment

good tutorial

View Tutorial          By: mohang at 2011-12-24 05:24:56
41. View Comment

Good Explanation of code. But object declaration inside while loop is not perfect. People may confuse but thanks for your post :)..

View Tutorial          By: Nitesh at 2011-12-28 12:37:09
42. View Comment

thanks excellent explanation!!!!!!!!

View Tutorial          By: divya at 2012-01-01 17:37:32
43. View Comment

good explanation,
Thanks


View Tutorial          By: venkatesh at 2012-01-04 08:43:48
44. View Comment

I would like to know how to obtain the object that the Iterator is actually referencing. Not all ArrayLists will be storing Strings, and no matter what I do I cannot obtain the object being referenced by that iterator.

For example, if my ArrayList is storing MyClass objects I want to do something like this:

Iterator iter = theArrayList.iterator();
MyClass current = (MyClass)iter; // <--- What do I do here?


View Tutorial          By: Steve at 2012-01-18 15:58:31
45. View Comment

Many thanks for your nice explanation.

View Tutorial          By: Zahra at 2012-04-10 06:03:56
46. View Comment

superb superb maza aggaya maza aggaya

View Tutorial          By: pramodh at 2012-04-16 05:21:54
47. View Comment

Very usefull info.. Thank alot

View Tutorial          By: Srikanth at 2012-09-04 15:44:30
48. View Comment

I am able to iterate the list.Now i want to print value on screen.How to do this?

View Tutorial          By: akanksha at 2012-09-26 05:25:12
49. View Comment

explanation is good but i have one doubt what is the use of Object in the program

View Tutorial          By: sulthan at 2012-10-09 06:13:14
50. View Comment

Thanks i had problem with this util module.

View Tutorial          By: james thompson at 2013-09-08 22:25:50
51. View Comment

Nice one.your example proves that if you are apply list iterator on collection object than one can change its run time behaviour.it simply means that collection object will become fail safe

Thank you


View Tutorial          By: Nisarg pathak at 2015-09-30 17:23:37

Your name (required):


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


Your sites URL (optional):


Your comments:



More Tutorials by Fazal
The Tag Life Cycle with Attributes in JSP
Using Shift Operators in C
IncludeAction in Struts
typedef example program in C
Arithmetic Evaluation Using the Expression Language in JSP
Tutorial on Complicated Declarations in C
Static Variables in C
getPosition() the right strategy in getting GPS
Precedence and Order of Evaluation in C
File Copying in C
JSF Life Cycle
Getting User Input Using cin in C++
UDP Datagram sample in J2ME
GUI components and menu based J2ME Applications.
A Serialization Example in Java

More Tutorials in Java
Update contents of a file within a jar file
Tomcat and httpd configured in port 8080 and 80
Java File
Java String
Count number of vowels, consonants and digits in a String in Java
Reverse a number in Java
Student marks calculation program in Java
Handling Fractions in Java
Calculate gross salary in Java
Calculate average sale of the week in Java
Vector in Java - Sample Program
MultiLevel Inheritance sample in Java
Multiple Inheritance sample in Java
Java program using Method Overriding
Java program to check if user input is an even number

More Latest News
Most Viewed Articles (in Java )
Integer: byte, short, int, and long data types in Java
Count number of vowels, consonants and digits in a String in Java
Stack example in Java - push(), pop(), empty(), search()
append() in Java
Using One-Dimensional Arrays in Java
XML and Java - Parsing XML using Java Tutorial
How to Send SMS using Java Program (full code sample included)
FileReader and FileWriter example program in Java
indexOf( ) and lastIndexOf( ) in Java
left shift operator, <<, in Java
Calendar - sample program in Java
TCP Server and TCP Client in Java
float vs double data types in Java
The switch Statement example in Java
Multidimensional or arrays of arrays in Java
Most Emailed Articles (in Java)
What is Java?
How to Send SMS using Java Program (full code sample included)
inheritance in Java
instanceof sample program in Java
Use of return statement in Java
Handling Fractions in Java
Using PrintWriter in Java
Method Overriding in Java
Using StringTokenizer in Java
Recursion in java
The java Buzzwords
Student marks calculation program in Java
Multiple Inheritance sample in Java
Java program to display numbers from 1 to 10 on Applet
emulator 0 terminated while waiting for it to register!