» » Iterator and Custom Iterator in java with example programs

Java Iterator 


  • Iterator is an interface which is made for Collection objects like List, Set. It comes inside java.util package and it was introduced in java 1.2 as public interface Iterator. To generate successive elements from a Collection, we can use java iterator. It contains three methods: those are, 

  1. boolean hasNext(): this method returns true if this Iterator has more element to iterate. 
  2. remove(): method remove the last element return by the iterator this method only calls once per call to next().     
  3. Object next() : Returns the next element in the iteration.
  • Every collection classes provides an iterator() method that returns an iterator to the beginning of the collection. By using this iterator object, we can access each element in the collection, one element at a time. In general, to use an iterator to traverse through the contents of a collection follow these steps:
  • Obtain Iterator object by calling Collections’s iterator() method
  • Make a loop to decide the next element availability by calling hasNext() method.
  •  Get each element from the collection by using next() method.
Java Program which explains how to use iterator in java

  • Here is an example demonstrating Iterator. It uses an ArrayList object, You can apply to any type of collection.

  1. import java.util.ArrayList;
  2. import java.util.Iterator;
  3.  
  4. public class IteratorExample {
  5.  
  6. public static void main(String args[]) {
  7.  
  8.  // create an array list. But, you can use any collection
  9.  ArrayList<String> arraylist = new ArrayList<String>();
  10.   
  11. // add elements to the array list
  12.  arraylist .add("Raja");
  13.  arraylist .add("Rani");
  14.  arraylist .add("Shankar");
  15.  arraylist .add("Uday");
  16.  arraylist .add("Philips");
  17.  arraylist .add("Sachin");
  18.  
  19. // use iterator to display contents of arraylist
  20.  System.out.println("Original contents of arraylist : ");
  21.  
  22. Iterator<String> itr = arraylist .iterator();
  23.  
  24.   while (itr.hasNext()) {
  25.  
  26.     Object obj = itr.next();
  27.      System.out.print(obj + "\n");
  28.  
  29.      }
  30.  
  31.  }
  32. }

 

Output:

  1. Original contents of arraylist : 
  2. Raja
  3. Rani
  4. Shankar
  5. Uday
  6. Philips
  7. Sachin


  •  Iterator is the best choice if you have to iterate the objects from a Collection. But, Iterator having some limitations.

  • Those are,
  1. Iterator is not index based 
  2.  If you need to update the collection object being iterated, normally you are not allowed to because of the way the iterator stores its position. And it will throw ConcurrentModificationException.
  3. It does not allow to traverse to bi directions.
custom ierator interface in java


  • To overcome these on other side,  we have For-each loop. It was introduced in Java 1.5
  • Advantages of For each loop :
  1. Index Based  
  2. Internally the for-each loop creates an Iterator to iterate through the collection.
  3. If you want to replace items in your collection objects, use for-each loop
  • Consider the following code snippet, to understand the difference between how to use Iterator and for-each loop. 



  1. Iterator<String> itr = aList.iterator();
  2.  
  3. while (itr.hasNext()) {
  4. Object obj = itr.next();
  5. System.out.print(obj + "\n");
  6. }
  7.  
  8. Is same as,
  9.  
  10. For (String str : aList){
  11. System.out.println(str);
  12. }

  • Same code has been rewritten using enhanced for-loops which looks more readable. But enhanced for-loops can’t be used automatically in Collection objects that we implement. Then what do we do? This is where Iterable interface comes in to picture. Only, if our Collection implemented Iterable interface, we can iterate using enhanced for-loops. The advantage of implementing Iterable interface So, we should implement Java Iterable interface in order to make our code more elegant.
  • Here I am going to write a best Practice to develop a custom iterator. Following is the Syntax.


  1. public class MyCollection<E> implements Iterable<E>{
  2.  
  3. public Iterator<E> iterator() {
  4.         return new MyIterator<E>();
  5.     }
  6.  
  7. public class MyIterator <T> implements Iterator<T> {
  8.  
  9.     public boolean hasNext() {
  10.     
  11.         //implement...
  12.     }
  13.  
  14.     public T next() {
  15.         //implement...;
  16.     }
  17.  
  18.     public void remove() {
  19.         //implement... if supported.
  20.     }
  21.  
  22. public static void main(String[] args) {
  23.     MyCollection<String> stringCollection = new MyCollection<String>();
  24.  
  25.     for(String string : stringCollection){
  26.     }
  27. }
  28. }
  29.  
  30. }


  1. package com.instanceofjava.customIterator;
  2.  
  3. public class Book {
  4.  
  5.     String name;
  6.     String author;
  7.     long isbn;
  8.     float price;
  9.    
  10.  
  11.     public Book(String name, String author, long isbn, float price) {
  12.         this.name = name;
  13.         this.author = author;
  14.         this.isbn = isbn;
  15.         this.price = price;
  16.     }
  17.  
  18.  public String toString() {
  19.         return name + "\t" + author + "\t" + isbn + "\t" + ": Rs" + price;
  20.   }
  21.  
  22. }

  1. package com.instanceofjava.customIterator;
  2. import java.util.ArrayList;
  3. import java.util.Iterator;
  4. import java.util.List;
  5. import com.pamu.test.Book;
  6. import java.lang.Iterable;
  7.  
  8. public class BookShop implements Iterable<Book> {
  9.  
  10.     List<Book> avail_books;
  11.  
  12.     public BookShop() {
  13.         avail_books = new ArrayList<Book>();
  14.     }
  15.  
  16.     public void addBook(Book book) {
  17.         avail_books.add(book);
  18.     }
  19.  
  20.     public Iterator<Book> iterator() {
  21.         return (Iterator<Book>) new BookShopIterator();
  22.     }
  23.  
  24.     class BookShopIterator implements Iterator<Book> {
  25.         int currentIndex = 0;
  26.  
  27.         @Override
  28.         public boolean hasNext() {
  29.             if (currentIndex >= avail_books.size()) {
  30.                 return false;
  31.             } else {
  32.                 return true;
  33.             }
  34.         }
  35.  
  36.         @Override
  37.         public Book next() {
  38.             return avail_books.get(currentIndex++);
  39.         }
  40.  
  41.         @Override
  42.         public void remove() {
  43.             avail_books.remove(--currentIndex);
  44.         }
  45.  
  46.     }
  47.     
  48.     //main method
  49.     
  50.   public static void main(String[] args) {
  51.  
  52.         Book book1 = new Book("Java", "JamesGosling", 123456, 1000.0f);
  53.         Book book2 = new Book("Spring", "RodJohnson", 789123, 1500.0f);
  54.         Book book3 = new Book("Struts", "Apache", 456789, 800.0f);
  55.  
  56.         BookShop avail_books = new BookShop();
  57.         avail_books.addBook(book1);
  58.         avail_books.addBook(book2);
  59.         avail_books.addBook(book3);
  60.  
  61.         System.out.println("Displaying Books:");
  62.         for(Book total_books : avail_books){
  63.             System.out.println(total_books);
  64.         }
  65.  
  66.     }
  67.  
  68. }

  • Here, we created a  BookShop class which contains books. This class able to use for-each loop only if it implements Iterable interface.Here, we have to provide the implementation for iterator method. we define my BookShopIterator as inner class.
  •  Inner classes will provide more security, So that your class is able to access with in the Outer class and this will achieve data encapsulation.
  • The best reusable option is to implement the interface Iterable and override the method iterator().The main advantage of Iterable is, when you implement Iterable then those object gets support for for:each loop syntax.
  • Execute above program and check output. Practice makes perfect.

Instance Of Java

We will help you in learning.Please leave your comments and suggestions in comment section. if you any doubts please use search box provided right side. Search there for answers thank you.
«
Next
Newer Post
»
Previous
Older Post

3 comments for Iterator and Custom Iterator in java with example programs

  1. I am searching for good example and explanation for custom iterator,It is very Help full Great article Thanks InstanceOfJava

    ReplyDelete
  2. Hi, Its very helpful for me, Thanks to instanceOfJava

    ReplyDelete
  3. After searching a long time for a good example, i found this one which is really helpful for me. Thanks for writing a good example...

    ReplyDelete

Select Menu