🔁 Iterator Design Pattern in Java

🔁 Iterator Design Pattern in Java

Navigating through elements of a collection without exposing its internal structure is where the Iterator Design Pattern shines. It’s one of the most widely used yet often overlooked patterns in day-to-day development.

Let’s break it down with examples and real-life parallels. 👇


💡 What is the Iterator Pattern?

The Iterator Pattern provides a way to access elements of a collection sequentially without exposing how the collection is implemented.

Instead of relying on complex loops or knowing about the data structure, you just ask the iterator: ➡️ “Do you have the next item?” ➡️ “What is it?”

This makes your code cleaner, more modular, and easier to maintain.


🧱 Structure

  • Iterator: Interface with methods like hasNext() and next().
  • ConcreteIterator: Implements the Iterator for a specific collection.
  • Aggregate/Collection: Holds the items and returns the iterator.

🌍 Real-World Analogies

1. TV Remote Control

  • Your remote has buttons to go to the next or previous channel.
  • You don't need to know how channels are stored in the TV.
  • The TV is the collection, the remote is the iterator.

2. Music Playlist

  • You skip forward/backward without knowing how songs are stored.
  • The music player provides the iterator interface.

3. Library Book Shelf

  • You scan books one by one, left to right.
  • You don’t need to understand the shelf’s construction—just take the next book.


import java.util.*;

// Song entity
class Song {
    private String title;

    public Song(String title) {
        this.title = title;
    }

    public String getTitle() {
        return title;
    }
}

// Playlist that implements Iterable
class MusicPlaylist implements Iterable<Song> {
    private List<Song> songs = new ArrayList<>();

    public void addSong(Song song) {
        songs.add(song);
    }

    @Override
    public Iterator<Song> iterator() {
        return songs.iterator(); // returning built-in iterator
    }
}

// Main player logic
public class Main {
    public static void main(String[] args) {
        MusicPlaylist playlist = new MusicPlaylist();
        playlist.addSong(new Song("Shape of You"));
        playlist.addSong(new Song("Blinding Lights"));
        playlist.addSong(new Song("Levitating"));

        System.out.println("🎶 Now Playing Playlist:");
        for (Song song : playlist) {
            System.out.println("→ " + song.getTitle());
        }
    }
}        

🧠 Why Use Iterator Pattern?

  • ✅ Hides collection internals
  • ✅ Unified way to traverse different structures
  • ✅ Simplifies client code
  • ✅ Supports safe iteration strategies in concurrent environments (with right tools)


📌 Final Thoughts

The Iterator Pattern is built into the foundation of Java’s Collection framework—so you’re already using it. But understanding its design intent empowers you to:

  • Write cleaner custom collections
  • Implement lazy or filtered iteration
  • Make thread-safe traversal decisions

Next time you loop through a collection—thank the Iterator Pattern. 😉

#Java #DesignPatterns #Iterator #CleanCode #OOP #SoftwareEngineering #ThreadSafety #LinkedInTech #ProgrammingTips #JavaDeveloper

To view or add a comment, sign in

More articles by Samartha Khare

Explore content categories