Register Now

Login

Lost Password

Enter your email to reset your password.

BY Author

Java – Iterator

Declaration

interface Iterator<E>

This interface supersedes the Enumeration interface.

With Enumeration we can only obtain elements one by one. But with Iterator interface we obtain as well as remove elements of a collection.

It cycles through the elements of the collection with the help of method explained below.

List of Iterator Methods (CLICK HERE)

Printing Elements using Iterator

Example

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

 public class IteratorInterfaceTest 
 {
     public static void main(String args[])
     {
         ArrayList<Integer> al = new ArrayList<Integer>();
         al.add(2);
         al.add(5);
         al.add(8);
         al.add(10);
         al.add(13);
         al.add(15);
         al.add(20);
		
         Iterator<Integer> itr = al.iterator();
         while(itr.hasNext())
         {
             Integer i = itr.next();
             System.out.println(i);
         }
     }
 }

Output

2
5
8
10
13
15
20

Removing Elements using Iterator

Example

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

 public class IteratorInterfaceTest2 
 {
     public static void main(String args[])
     {
         ArrayList<Integer> al = new ArrayList<Integer>();
         al.add(2);
         al.add(5);
         al.add(8);
         al.add(10);
         al.add(13);
         al.add(15);
         al.add(20);
		
         System.out.println(al);
        
         Iterator<Integer> itr = al.iterator();
         while(itr.hasNext())
         {
             Integer i = itr.next();
             if(i>10)
             {
                 itr.remove();
             }
         }
        
         System.out.println(al);
     }
 }

Output

[2, 5, 8, 10, 13, 15, 20]
[2, 5, 8, 10]

 

Leave a reply