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
Please enter at least three characters to search
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

Because the DevOps movement has redefined engineering responsibilities, SREs now have to become stewards of observability strategy.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Related

  • Introducing Graph Concepts in Java With Eclipse JNoSQL, Part 3: Understanding Janus
  • Introducing Graph Concepts in Java With Eclipse JNoSQL, Part 2: Understanding Neo4j
  • How to Introduce a New API Quickly Using Micronaut
  • Introducing Graph Concepts in Java With Eclipse JNoSQL

Trending

  • Implementing Explainable AI in CRM Using Stream Processing
  • Designing a Java Connector for Software Integrations
  • How To Build Resilient Microservices Using Circuit Breakers and Retries: A Developer’s Guide To Surviving
  • AI Agents: A New Era for Integration Professionals
  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
Likes (1)
Comment
Save
Tweet
Share
61.6K 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

  • Introducing Graph Concepts in Java With Eclipse JNoSQL, Part 3: Understanding Janus
  • Introducing Graph Concepts in Java With Eclipse JNoSQL, Part 2: Understanding Neo4j
  • How to Introduce a New API Quickly Using Micronaut
  • Introducing Graph Concepts in Java With Eclipse JNoSQL

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and 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:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!