DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Java 27 Makes G1 the Default Everywhere: How to Test Your Small Containers Before You Upgrade
  • Stop Writing Database Migration Scripts: Declarative Schema Sync for Java
  • Searching Kafka Without an Index: Lessons From Building Message Search for Kafdrop
  • ScyllaDB in Enterprise Java: High-Performance NoSQL With Eclipse JNoSQL

Trending

  • The SDLC After AI
  • Applying Microservices Lessons to Multi-Agent AI Systems
  • Beyond Manual Mapping: AI-Orchestrated Governance for Hybrid Cloud
  • Idempotency Under Concurrency: Why Your Application Check Isn't the Last Line of Defense

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  1. DZone
  2. Coding
  3. Java
  4. Iterator Pattern Tutorial with Java Examples

Iterator Pattern Tutorial with Java Examples

Learn the Iterator Design Pattern with easy Java source code examples as James Sugrue continues his design patterns tutorial series, Design Patterns Uncovered

By 
James Sugrue
·
Jun. 03, 10 · Tutorial
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
62.5K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

Today's pattern is the Iterator pattern which formalizes how we move through a collection of data in a particular class

Iterator in the Real World 

MP3 player control is a good example of an iterator. The user doesn't mind how to view their list of songs, once they get to see them somehow. In older mp3 players, this was done using simple forward and back buttons. With the iPod this changed to the wheel navigation concept. The iPhone moves this on further to use swipe movements. Nevertheless, the same idea is provided by all interfaces - a way to iterate through your music collection.

Design Patterns Refcard
For a great overview of the most popular design patterns, DZone's Design Patterns Refcard is the best place to start. 

The Iterator Pattern

The Iterator pattern is known as abehavioural pattern, as it's used to manage algorithms, relationships and responsibilities between objects.. Thedefinition of Iterator as provided in the original Gang of Four book on DesignPatterns states: 

Provides a way to access the elements of an aggregate object without exposing its underlying represenation.

Let's take a look at the diagram definition before we go into more detail.

The Aggregate defines an interface for the creation of the Iterator object. The ConcreteAggregate implements this interface, and returns an instance of the ConcreteIterator. The Iterator defines the interface for access and traversal of the elements, and the ConcreteIterator implements this interface while keeping track of the current position in the traversal of the Aggregate.

Using this pattern, you can build on the standard concept of iteration to define special iterators that only return specific elements in the data set.

Would I Use This Pattern?

This pattern is useful when you need access to elements in a set without access to the entire representation. When you need a uniform traversal interface, and multiple traversals may happen across elements, iterator is a good choice. 

It also makes you code much more reasonable, getting rid of the typical for loop syntax across sections of your codebase.

So How Does It Work In Java?

Java provides an implementation of the Iterator pattern, which provides next() and hasNext() methods. Creation of the iterator in Java is typically done through a method named iterator() in the container class.
The following example shows use of an iterator with a list : 

List<String> list = new ArrayList<String>();//add strings Iterator it = list.iterator();while(it.hasNext()){   String s = it.next();}

Now let's go to an example where we create the constructs ourselves, with a remote control example.
First we'll create an iterator with the standard methods:

//Iterator interface public interface ChannelIterator{public boolean hasNext();public void next();public String currentItem();}

Next we create the Aggregate interface, in this case a TV. 

//Aggregate interfacepublic interface TV{public Channel getIterator();//other TV methods}

The concrete implementation of the aggregator has the capability to create the iterator

//Concrete Aggregatorpublic class ConcreteTV{private ChannelIterator iterator; private List<String> channels; public ConcreteTV(){iterator = new ConcreteChannelIterator(channels);}public ChannelIterator getIterator(){return iterator;}}

Finally the iterator helps control how we navigate the data. 

//Concrete Iterator //Iterator interface public interface ChannelIterator{private List<String> channels; private int currentPos = 0; public ChannelIterator(List<String> channels){this.channels = channels;}public boolean hasNext(){if(currentPos + 1 < channels.size()){return true;}return false;}public void next(){currentPos++;}public String currentItem(){return channels.get(currentPos);}}

Of course this is a one-way remote control. We could implement back() and hasBack() methods to navigate backwards in our iterator. 

Watch Out for the Downsides

I don't see any disadvantages to this pattern. It's simple, widely used and provides more readable code. However, you may disagree - if so, please let me know in the comments section.

Next Up

We've only two patterns left, so the penultimate pattern in our series will be the State pattern.

Enjoy the Whole "Design Patterns Uncovered" Series:

Creational Patterns

  • Learn The Abstract Factory Pattern
  • Learn The Builder Pattern
  • Learn The Factory Method Pattern
  • Learn The Prototype Pattern
  • Learn The Singleton Pattern

Structural Patterns

  • Learn The Adapter Pattern
  • Learn The Bridge Pattern
  • Learn The Composite Pattern
  • Learn The Decorator Pattern
  • Learn The Facade Pattern
  • Learn The Flyweight Pattern
  • Learn The Proxy Pattern

Behavioral Patterns

  • Learn The Chain of Responsibility Pattern
  • Learn The Command Pattern
  • Learn The Interpreter Pattern
  • Learn The Iterator Pattern
  • Learn The Mediator Pattern
  • Learn The Memento Pattern
  • Learn The Observer Pattern
  • Learn The State Pattern
  • Learn The Strategy Pattern
  • Learn The Template Method Pattern
  • Learn The Visitor Pattern
Java (programming language)

Opinions expressed by DZone contributors are their own.

Related

  • Java 27 Makes G1 the Default Everywhere: How to Test Your Small Containers Before You Upgrade
  • Stop Writing Database Migration Scripts: Declarative Schema Sync for Java
  • Searching Kafka Without an Index: Lessons From Building Message Search for Kafdrop
  • ScyllaDB in Enterprise Java: High-Performance NoSQL With Eclipse JNoSQL

Partner Resources

×

Comments

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook