Home Tutorial Java Core Collection : Iterator Example

 
 

Share on Google+Share on Google+
Collection : Iterator Example
Posted on: November 19, 2012 at 12:00 AM
Advertisement
In this section we will discuss Iterator with example.

Collection : Iterator Example

In this section we will discuss Iterator with example.

Iterator :

Iterator interface is a member of the Java Collection Framework. It takes place of Enumeration but it differ from enumeration.
It is used to iterate the elements of your list. By using Iterator we can traverse only one direction. Its execution end when it reached the end of series.

hasNext() : It returns true if the iteration has more elements.

next()  : It returns the next element in the iteration.

remove() : It removes the most recent element that was returned by next .

Example :

package collection;

import java.util.ArrayList;
import java.util.Iterator;

class IteratorExample {
public static void main(String[] args) {

ArrayList list = new ArrayList();
list.add("Apple");
list.add("Orange");
list.add("Mango");
list.add("Pineapple");

Iterator it = list.iterator();
System.out.println("List of fruits : ");
while (it.hasNext()) {
System.out.println(it.next());
}
}
}

Description : In this example we are using Iterator to print elements of ArrayList.  By calling the collection's iterator we can obtain iterator to start the collection.
Next to setup the loop and call hasNext() method to iterate the loop. It will iterate till hasNext() returns false.
Within loop you can call each element by calling next() method

Output :

List of fruits : 
Apple
Orange
Mango
Pineapple
Advertisement

Related Tags for Collection : Iterator Example:


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: November 19, 2012

Recommend the tutorial

Advertisements Advertisements
 

 

 

DMCA.com