Collection : Iterator Example


 

Collection : Iterator Example

In this section we will discuss Iterator with example.

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

Ads