Home Java Example Java Util Java List Iterator Example



Java List Iterator Example
Posted on: November 4, 2011 at 12:00 AM
In this tutorial you will learn how to iterate data from a list

Java List Iterator Example

In Java Collection framework every classes provides the iterator() method, that returns the objects of iterator which used to start the collection. By using this iterator objects you can access each element in a collection.

An example given below

At fist make an object and add some data into it as

// Declaring ArrayList object of type String
List myList = new ArrayList();

Then add some elements of type String into it as

// Adding elements to the list
		
myList.add("Rohan");
myList.add("Johan");
myList.add("Sams");
myList.add("Ram");
myList.add("Ramesh");
myList.add("Andrew");

Now call the iterator() method of list and store the result into the Iterator object as

/********** Iteration **********/
Iterator iterator = myList.iterator();

This method returns the iterator object which is used to start the collection

To access all the elements stored in a list apply the loop as

while (iterator.hasNext()) {
		System.out.println(iterator.next());
	}

Please note the method used above of iterator objects, hasNext() and next()

The hasNext() method returns true if any element present in the loop and the next() method returns the next element from the collection

There are more methods present in the iterator interface, to read them please visit the Sun or Oractle site


When you run this application it will display message as shown below:


Rohan
Johan
Sams
Ram
Ramesh
Andrew

Download Select Source Code

Related Tags for Java List Iterator Example:


More Tutorials from this section

Ask Questions?    Discuss: Java List Iterator Example  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 

Ask Questions?

If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.

Ask your questions, our development team will try to give answers to your questions.