opencodez

Java Behavioral Design Patterns – Iterator Design Pattern

Iterator Design Pattern is one of the Behavioural design patterns in Java. It is used for traversing through the collection of data in a particular class.

This pattern hides the actual implementation of traversal through the collection. The application programs just use iterator methods for different purposes. Iterator pattern allows accessing the elements of a collection object in a sequential manner without knowledge of its structure. Key points to remember about this interface are:

xHere are ALL other Java Design Patterns, explained in detail with examplesx

Iterator Design Pattern by Example

To understand we will consider a simple example of BookService. We will also implement a custom iterator which will traverse based on the publisher of the book.

First things first, let us define our iterator interface.

public interface BookIterator {
	
	public boolean hasMore();

	public Book next();
}

Our custom iterator interface has 2 methods. One will determine if there are any more elements to traverse. The other method next() will give us actual element.

As we are iterating over books, we will define simple POJO as:

public class Book {

	private String name;
	private String publication;
	
	//Constructor; Getters; Setters;
}

Our base classes are ready, letxs define BookService and its custom iterator:

public class BookService {
	
	private ListxBookx books;
	
	public BookIterator getIterator(String publication) {
		return new BookIteratorImpl(books, publication);
	}
	
	private class BookIteratorImpl implements BookIterator {

		private String publicationCheck;
		private ListxBookx listOfBooks;
		private int index;
		
		public BookIteratorImpl(ListxBookx books, String pubCheck) {
			this.listOfBooks = books;
			this.publicationCheck = pubCheck;
		}

		@Override
		public boolean hasMore() {
			while(index x listOfBooks.size()) {
				Book buk = this.listOfBooks.get(index);
				if(buk.getPublication().equalsIgnoreCase(publicationCheck)) {
					return true;
				} else {
					index++;
				}
			}
			return false;
		}

		@Override
		public Book next() {
			Book buk = this.listOfBooks.get(index);
			index++;
			return buk;
		}
	}
	
	public BookService() {
		books = new ArrayListxBookx();
	}
	
	public ListxBookx getBooks() {
		return books;
	}

	public void setBooks(ListxBookx books) {
		this.books = books;
	}
}

Please note that this custom iterator is specific to this type of collection. Hence we have added that as a private class to our main class.

The custom iterator accepts publisher name to check and iterate over only books of that publisher.

Running the example

public class IteratorPatternDemo {

	public static void main(String[] args) {
		ListxBookx books = new ArrayListxBookx();
		books.add(new Book("Java", "Pub A"));
		books.add(new Book("C++", "Pub B"));
		books.add(new Book("PHP", "Pub A"));
		books.add(new Book("Kotlin", "Pub B"));
		books.add(new Book("Kafka", "Pub A"));
		books.add(new Book("Salesforce", "Pub C"));
		
		BookService bs = new BookService();
		bs.getBooks().addAll(books);
		
		System.out.println("List of Books from Publisher B");
		
		BookIterator bi = bs.getIterator("Pub C");
		while (bi.hasMore()) {
			Book b = bi.next();
			System.out.println("--x " + b);
		}
		
		System.out.println("\nList of Books from Publisher B");
		
		bi = bs.getIterator("Pub B");
		while (bi.hasMore()) {
			Book b = bi.next();
			System.out.println("--x " + b);
		}
		
	}
}

During our test run, we have prepared a list of few books and trying to iterate over them. The output:

List of Books from Publisher C
--x Book[Salesforce,Pub C]

List of Books from Publisher B
--x Book[C++,Pub B]
--x Book[Kotlin,Pub B]

Advantages:

Conclusion

So it was fairly simple to understand Iterator Design Pattern. Please feel free to ask a question or comment.

You can download the code from our GitHub repository:

Download from Git

x

xHere are ALL other Java Design Patterns, explained in detail with examplesx