How to implement Iterator and Iterable Interface in Java

In this tutorial, we will learn about iterator and iterable interfaces in Java along with example programs.
Java iterator is available since Java 1.2 collection framework. Whereas the iterable interface in Java was introduced in Java version 5.

Iterator

Iterator is used to access the elements of a collection. Every collection class has iterator methods to cycle through the collection, obtain or remove elements. Iterator class in Java belongs to java.util package. The methods declared by the iterator class are as follows,

boolean hasNext() – It returns true if there exists a next element in the collection otherwise returns false.
object next() – It returns the next element in the collection and displays an error message when no more element is present.
void remove() – It removes the current element pointed by the iterator. It displays an error message if the iterator is empty.

Let us see an example program that utilizes the above-mentioned methods,

import java.util.*;  
  
public class IteratorExample {  
   public static void main(String[] args) {  
 
   // Creating a container    
   ArrayList<String> Mylist = new ArrayList<String>();  

   // Adding Elements
   Mylist.add("Hello ");  
   Mylist.add("Welcome ");  
   Mylist.add("To ");  
   Mylist.add("CodeSpeedy. ");  

    // Declaring Iterator
    Iterator<String> iter = Mylist.iterator();  
     
    //Returns true if next element is present  
    while(iter.hasNext()) {  
       //Returns the next element  
       System.out.print(iter.next());  
       }  
       
    //Removes last element   
    iter.remove();   
     
   }  
}

Output

Hello Welcome To CodeSpeedy.

Iterable Interface

The for loop in Java can be utilized to process different kinds of data structures. In order to use for loop to iterate over certain class, the class must implement the iterable interface. We use for-each loop for iterating over objects of the implemented class. Iterables does not have a current state, rather it delivers an iterator.
Steps to implement Iterable interface,
1. Implement an iterable interface using the class whose object needs access to foreach loop.
2. Override the iterator() method defined in the class that implements the iterable interface.
3. The iterable does not maintain a current state so return an instance of iterator() method.

Therefore by carefully following these steps, we can successfully implement an iterable interface.
Let us see an example program that follows the implementation steps mentioned above,

import java.util.*;

// Implementing iterable interface
class CodeSpeedy<T> implements Iterable<T> {
 
    private List<T> strList;
 
    public CodeSpeedy(T [] temp) {
 
        strList = Arrays.asList(temp);
        
    }
    
    //Overriding iterator()  
    @Override
    public Iterator<T> iterator() {
 
        return strList.iterator();
    }
}
public class Main {
 
    public static void main(String [] args) {
 
        String [] str = {"Welcome ", "To ", "CodeSpeedy. "};
        
        // Object Declaration   
        CodeSpeedy<String> obj = new CodeSpeedy<>(str);
 
        //For-each loop
        for (String i : obj) {
 
            System.out.print(i);
        }
    }
}

Output

After completing the code, we can run it. Below is what we can see in the output:

Welcome To CodeSpeedy.

 

You can also learn about Enumeration Interface in Java by clicking the link.

 

Leave a Reply