WikiGalaxy

Personalize

Java Iterator: Introduction

What is an Iterator?

In Java, an Iterator is an interface that provides methods to iterate over any Collection. It allows you to traverse through a collection and remove elements from the collection.

Why use an Iterator?

Iterators are used to process collections of objects in a standardized way. They provide a way to access elements without exposing the underlying representation.


import java.util.*;
class IteratorExample {
    public static void main(String args[]) {
        List list = new ArrayList<>();
        list.add("Apple");
        list.add("Banana");
        list.add("Cherry");

        Iterator iterator = list.iterator();
        while (iterator.hasNext()) {
            System.out.println(iterator.next());
        }
    }
}
    

Console Output:

Apple Banana Cherry

Removing Elements Using Iterator

Why Remove Elements with Iterator?

Removing elements from a collection while iterating can lead to ConcurrentModificationException. Using Iterator's remove method prevents this issue.


import java.util.*;
class IteratorRemoveExample {
    public static void main(String args[]) {
        List list = new ArrayList<>();
        list.add("Dog");
        list.add("Cat");
        list.add("Rabbit");

        Iterator iterator = list.iterator();
        while (iterator.hasNext()) {
            String animal = iterator.next();
            if ("Cat".equals(animal)) {
                iterator.remove();
            }
        }
        System.out.println(list);
    }
}
    

Console Output:

[Dog, Rabbit]

Using Iterator with Set

Iterating Over a Set

Sets do not maintain an order of elements, but you can still use an Iterator to traverse them.


import java.util.*;
class SetIteratorExample {
    public static void main(String args[]) {
        Set set = new HashSet<>();
        set.add("Red");
        set.add("Green");
        set.add("Blue");

        Iterator iterator = set.iterator();
        while (iterator.hasNext()) {
            System.out.println(iterator.next());
        }
    }
}
    

Console Output:

Red Green Blue

Iterator vs For-Each Loop

Comparison with For-Each Loop

While the for-each loop is simpler, it doesn't allow removal of elements during iteration. Iterator provides more control.


import java.util.*;
class IteratorVsForEach {
    public static void main(String args[]) {
        List list = new ArrayList<>();
        list.add("X");
        list.add("Y");
        list.add("Z");

        for (String s : list) {
            System.out.println(s);
        }

        Iterator iterator = list.iterator();
        while (iterator.hasNext()) {
            System.out.println(iterator.next());
        }
    }
}
    

Console Output:

X Y Z X Y Z

Using Iterator with Map

Iterating Over a Map

Maps require a different approach as they store key-value pairs. Use entrySet, keySet, or values for iteration.


import java.util.*;
class MapIteratorExample {
    public static void main(String args[]) {
        Map map = new HashMap<>();
        map.put(1, "One");
        map.put(2, "Two");
        map.put(3, "Three");

        Iterator> iterator = map.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry entry = iterator.next();
            System.out.println(entry.getKey() + " = " + entry.getValue());
        }
    }
}
    

Console Output:

1 = One 2 = Two 3 = Three

Iterator with LinkedList

Benefits with LinkedList

LinkedList allows bidirectional iteration using ListIterator, providing more flexibility.


import java.util.*;
class LinkedListIteratorExample {
    public static void main(String args[]) {
        LinkedList list = new LinkedList<>();
        list.add("Monday");
        list.add("Tuesday");
        list.add("Wednesday");

        ListIterator iterator = list.listIterator();
        while (iterator.hasNext()) {
            System.out.println(iterator.next());
        }
    }
}
    

Console Output:

Monday Tuesday Wednesday

Custom Iterator Implementation

Creating a Custom Iterator

Implementing your own Iterator can be useful when you need custom traversal logic for your data structures.


import java.util.*;
class CustomIterator implements Iterator {
    private int[] numbers;
    private int index;

    public CustomIterator(int[] numbers) {
        this.numbers = numbers;
        this.index = 0;
    }

    @Override
    public boolean hasNext() {
        return index < numbers.length;
    }

    @Override
    public Integer next() {
        if (!hasNext()) {
            throw new NoSuchElementException();
        }
        return numbers[index++];
    }
}

class CustomIteratorExample {
    public static void main(String args[]) {
        int[] numbers = {10, 20, 30};
        CustomIterator iterator = new CustomIterator(numbers);

        while (iterator.hasNext()) {
            System.out.println(iterator.next());
        }
    }
}
    

Console Output:

10 20 30

Using Iterator for Concurrent Collections

Concurrent Collection Iteration

Iterators for concurrent collections like ConcurrentHashMap are fail-safe, meaning they don't throw ConcurrentModificationException.


import java.util.concurrent.*;
class ConcurrentIteratorExample {
    public static void main(String args[]) {
        ConcurrentHashMap map = new ConcurrentHashMap<>();
        map.put("A", 1);
        map.put("B", 2);
        map.put("C", 3);

        Iterator iterator = map.keySet().iterator();
        while (iterator.hasNext()) {
            System.out.println(iterator.next());
        }
    }
}
    

Console Output:

A B C

Iterator Limitations

Understanding Iterator Limitations

Iterators can only move forward, and they do not support adding elements during iteration. For more complex operations, consider using ListIterator.


import java.util.*;
class IteratorLimitationsExample {
    public static void main(String args[]) {
        List list = new ArrayList<>();
        list.add("Alpha");
        list.add("Beta");

        ListIterator listIterator = list.listIterator();
        while (listIterator.hasNext()) {
            System.out.println(listIterator.next());
            listIterator.add("Gamma");
        }

        System.out.println(list);
    }
}
    

Console Output:

Alpha Beta [Alpha, Gamma, Beta, Gamma]

logo of wikigalaxy

Newsletter

Subscribe to our newsletter for weekly updates and promotions.

Privacy Policy

 • 

Terms of Service

Copyright © WikiGalaxy 2025