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
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Low-Code Development: Leverage low and no code to streamline your workflow so that you can focus on higher priorities.

DZone Security Research: Tell us your top security strategies in 2024, influence our research, and enter for a chance to win $!

Launch your software development career: Dive head first into the SDLC and learn how to build high-quality software and teams.

Open Source Migration Practices and Patterns: Explore key traits of migrating open-source software and its impact on software development.

Related

  • Maven Archetypes: Simplifying Project Template Creation
  • How To Remove Excel Worksheets Using APIs in Java
  • Javac and Java Katas, Part 2: Module Path
  • Twenty Things Every Java Software Architect Should Know

Trending

  • What Is Plagiarism? How to Avoid It and Cite Sources
  • Handling “Element Is Not Clickable at Point” Exception in Selenium
  • Microservices Design Patterns for Highly Resilient Architecture
  • Test Smells: Cleaning up Unit Tests
  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 user avatar
James Sugrue
DZone Core CORE ·
Jun. 03, 10 · Tutorial
Like (1)
Save
Tweet
Share
61.1K Views

Join the DZone community and get the full member experience.

Join For Free

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

  • Maven Archetypes: Simplifying Project Template Creation
  • How To Remove Excel Worksheets Using APIs in Java
  • Javac and Java Katas, Part 2: Module Path
  • Twenty Things Every Java Software Architect Should Know

Partner Resources


Comments

ABOUT US

  • About DZone
  • Send feedback
  • Community research
  • Sitemap

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 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: