Iterator Design Pattern Tutorial

Iterator Design Pattern TutorialWelcome to my Iterator Design Pattern Tutorial! The iterator design pattern allows you to access objects that are stored in many different collection types.

You do this by creating a common interface that these classes share. Then you have them provide you with an iterator that allows you to traverse the objects they contain.

Because they all share a common interface you can treat them polymorphically and eliminate a lot of duplicate code. The example video will explain how and the code that follows will reenforce the concepts.

If you like videos like this, it helps to tell Google [googleplusone]

Share it if you think others will find it useful

Code from the Video


// Will hold all of the info needed for each song

// I told all users to:
// 1. create a function named addSong() for adding song, band and release
// 2. create a function named getBestSongs() that will return the collection
//    of songs

public class SongInfo{
	String songName; 
	String bandName; 
	int yearReleased;
	public SongInfo(String newSongName, String newBandName, int newYearReleased){
		songName = newSongName;
		bandName = newBandName;
		yearReleased = newYearReleased;
	public String getSongName(){ return songName; }
	public String getBandName(){ return bandName; }
	public int getYearReleased(){ return yearReleased; }


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

public class SongsOfThe70s implements SongIterator{
	// ArrayList holds SongInfo objects
	ArrayList<SongInfo> bestSongs;
	public SongsOfThe70s() {
		bestSongs = new ArrayList<SongInfo>();
		addSong("Imagine", "John Lennon", 1971);
		addSong("American Pie", "Don McLean", 1971);
		addSong("I Will Survive", "Gloria Gaynor", 1979);
	// Add a SongInfo object to the end of the ArrayList
	public void addSong(String songName, String bandName, int yearReleased){
		SongInfo songInfo = new SongInfo(songName, bandName, yearReleased);
	// Get rid of this
	// Return the ArrayList filled with SongInfo Objects
	public ArrayList<SongInfo> getBestSongs(){
		return bestSongs;

	// NEW By adding this method I'll be able to treat all
	// collections the same
	public Iterator createIterator() {
		// TODO Auto-generated method stub
		return bestSongs.iterator();


import java.util.Arrays;
import java.util.Iterator;

public class SongsOfThe80s implements SongIterator{
	// Create an array of SongInfo Objects
	SongInfo[] bestSongs;
	// Used to increment to the next position in the array
	int arrayValue = 0;
	public SongsOfThe80s() {
		bestSongs = new SongInfo[3];
		addSong("Roam", "B 52s", 1989);
		addSong("Cruel Summer", "Bananarama", 1984);
		addSong("Head Over Heels", "Tears For Fears", 1985);
	// Add a SongInfo Object to the array and increment to the next position
	public void addSong(String songName, String bandName, int yearReleased){
		SongInfo song = new SongInfo(songName, bandName, yearReleased);
		bestSongs[arrayValue] = song;
	// This is replaced by the Iterator
	public SongInfo[] getBestSongs(){
		return bestSongs;

	// NEW By adding this method I'll be able to treat all
	// collections the same
	public Iterator createIterator() {
		// TODO Auto-generated method stub
		return Arrays.asList(bestSongs).iterator();	


import java.util.Hashtable;
import java.util.Iterator;

public class SongsOfThe90s implements SongIterator{
	// Create a Hashtable with an int as a key and SongInfo
	// Objects 
	Hashtable<Integer, SongInfo> bestSongs = new Hashtable<Integer, SongInfo>();
	// Will increment the Hashtable key
	int hashKey = 0;
	public SongsOfThe90s() {
		addSong("Losing My Religion", "REM", 1991);
		addSong("Creep", "Radiohead", 1993);
		addSong("Walk on the Ocean", "Toad The Wet Sprocket", 1991);
	// Add a new SongInfo Object to the Hashtable and then increment
	// the Hashtable key
	public void addSong(String songName, String bandName, int yearReleased){
		SongInfo songInfo = new SongInfo(songName, bandName, yearReleased);
		bestSongs.put(hashKey, songInfo);
	// This is replaced by the Iterator
	// Return a Hashtable full of SongInfo Objects
	public Hashtable<Integer, SongInfo> getBestSongs(){
		return bestSongs;

	// NEW By adding this method I'll be able to treat all
	// collections the same
	public Iterator createIterator() {
		// TODO Auto-generated method stub
		return bestSongs.values().iterator();


import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Iterator;

public class DiscJockey {
	SongsOfThe70s songs70s;
	SongsOfThe80s songs80s;
	SongsOfThe90s songs90s;
	// NEW Passing in song iterators
	SongIterator iter70sSongs;
	SongIterator iter80sSongs;
	SongIterator iter90sSongs;
	public DiscJockey(SongsOfThe70s newSongs70s, SongsOfThe80s newSongs80s, SongsOfThe90s newSongs90s) {
		songs70s = newSongs70s;
		songs80s = newSongs80s;
		songs90s = newSongs90s;
	// NEW WAY Initialize the iterators	
	public DiscJockey(SongIterator newSongs70s, SongIterator newSongs80s, SongIterator newSongs90s) {
		iter70sSongs = newSongs70s;
		iter80sSongs = newSongs80s;
		iter90sSongs = newSongs90s;
	public void showTheSongs(){
		// Because the SongInfo Objects are stored in different
		// collections everything must be handled on an individual
		// basis. This is BAD!
		ArrayList aL70sSongs = songs70s.getBestSongs();
		System.out.println("Songs of the 70s\n");
		for(int i=0; i < aL70sSongs.size(); i++){
			SongInfo bestSongs = (SongInfo) aL70sSongs.get(i);
			System.out.println(bestSongs.getYearReleased() + "\n");
		SongInfo[] array80sSongs = songs80s.getBestSongs();
		System.out.println("Songs of the 80s\n");
		for(int j=0; j < array80sSongs.length; j++){
			SongInfo bestSongs = array80sSongs[j];
			System.out.println(bestSongs.getYearReleased() + "\n");
		Hashtable<Integer, SongInfo> ht90sSongs = songs90s.getBestSongs();
		System.out.println("Songs of the 90s\n");
		for (Enumeration<Integer> e = ht90sSongs.keys(); e.hasMoreElements();)
			SongInfo bestSongs = ht90sSongs.get(e.nextElement());
			System.out.println(bestSongs.getYearReleased() + "\n");
	// Now that I can treat everything as an Iterator it cleans up
	// the code while allowing me to treat all collections as 1
	public void showTheSongs2(){
		System.out.println("NEW WAY WITH ITERATOR\n");
		Iterator Songs70s = iter70sSongs.createIterator();
		Iterator Songs80s = iter80sSongs.createIterator();
		Iterator Songs90s = iter90sSongs.createIterator();
		System.out.println("Songs of the 70s\n");
		System.out.println("Songs of the 80s\n");
		System.out.println("Songs of the 90s\n");
	public void printTheSongs(Iterator iterator){
			SongInfo songInfo = (SongInfo);
			System.out.println(songInfo.getYearReleased() + "\n");


public class RadioStation {
	public static void main(String[] args){
		SongsOfThe70s songs70s = new SongsOfThe70s();
		SongsOfThe80s songs80s = new SongsOfThe80s();
		SongsOfThe90s songs90s = new SongsOfThe90s();
		DiscJockey madMike = new DiscJockey(songs70s, songs80s, songs90s);
		// madMike.showTheSongs();


import java.util.Iterator;

public interface SongIterator {
	public Iterator createIterator();

35 Responses to “Iterator Design Pattern Tutorial”

  1. DTP says:

    Just wanted to say thanks for all your work.
    So thanks.

  2. SJA says:

    Great job! very nice stuff on design patterns. Thanks a ton.

    • admin says:

      You’re very welcome 🙂 I’m finishing up object oriented design today. Then the next tutorial will be on code refactoring, which will help you incorporate design patterns into your designs.

  3. atif says:

    WoooW , This is absolutely Great .
    Thank you so much sir ,
    Hats Off 🙂
    You’Re The Man , You’Re The Best .
    Keep up the good work !

  4. sudhakaran says:

    I have always found your videos and code on design patterns to be very concise and to the point. Please continue your good work, and thanks a ton !


  5. Manesh says:

    Another Great article.. Thoroughly explained..

  6. dhafar says:

    Thank you
    because description very nice

  7. Sourabh Sharma says:

    Derek you are just amazing 😀

  8. Yohannes says:

    really swift,fast and great tutorials, u r simply great dude!

  9. Yohannes says:

    great job…thanks for ur time

  10. Nikki says:

    Another great tutorial! You make it look so easy! Thanks again!

  11. Sam says:

    Thanks great tutorials, please keep up the good work

  12. Nicat says:

    Hello. Great job. Mr Derek. Can u share the UML schema of that design Pattern too ? I did. And i want check mine.

  13. Ga says:

    Thank you SO MUCH for all your veideos. I am amazed that people take their time to do this for everyone to benefit. I feel like you are providing great content and great help. Thank you so much!

    P.S. This helps a lot with exam revision too!

    • Derek Banas says:

      You’re very welcome 🙂 I have continued to do this because I have found so many wonderful people on the internet that I have not found any place else. I’m more then happy to help.

  14. Martin Petersen says:

    You are a god;)

  15. Omar says:

    you’re awesome! i watched practically all your design patterns videos.thumbs up! 😉

  16. Chandan says:

    Actually you’ve created a new Learning pattern ;). Doesn’t matter How much complicated the topic is, just watch the video once and then go through the code, you get it. Good work Derek!

Leave a Reply

Your email address will not be published.