Implementing custom iterators

Implementing custom iterators in Java involves creating classes that implement the Iterator interface or extend classes that provide iterator functionality (Iterator or ListIterator). Custom iterators are useful when you need to define specialized traversal logic or filter elements during iteration.

Let’s create an example of a custom iterator for a list of student names.

import java.util.*;
class CustomStudentIterator implements Iterator<String> {

    private final List<String> students;
    private int currentIndex;

    public CustomStudentIterator(List<String> students) {
        this.students = students;
        this.currentIndex = 0;
    }

    @Override
    public boolean hasNext() {
        return currentIndex < students.size();
    }

    @Override
    public String next() {
        if (!hasNext()) {
            throw new IndexOutOfBoundsException("No more elements to iterate");
        }
        return students.get(currentIndex++);
    }

    @Override
    public void remove() {
        students.remove(--currentIndex);
    }
}



public class CustomIteratorExample {

    public static void main(String[] args) {
        // Using CustomStudentList
        List<String> studentList = new LinkedList();
        studentList.add("Paani");
        studentList.add("Mahesh");
        studentList.add("Datta");

        System.out.println("Student List:");
        // Using custom iterator
        CustomStudentIterator iterator = new CustomStudentIterator(studentList);
        while (iterator.hasNext()) {
            String student = iterator.next();
            System.out.println(student);
        }

        // Using CustomStudentSet
        Set<String> studentSet = new HashSet();
        studentSet.add("Ganesh");
        studentSet.add("Harsha");
        studentSet.add("Paani"); // Adding duplicate should not be added in set

        System.out.println("\nStudent Set:");
        for (String student : studentSet) {
            System.out.println(student);
        }
    }
}

/*
D:\javaplanet\Collection Framework>javac CustomIteratorExample.java
Note: CustomIteratorExample.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.

D:\javaplanet\Collection Framework>java CustomIteratorExample
Student List:
Paani
Mahesh
Datta

Student Set:
Ganesh
Harsha
Paani
*/

Implementing custom iterators allows you to extend the functionality of Java’s standard collection classes or create entirely new collection classes with specialized iteration behaviors, tailored to the needs of your application.

Scroll to Top