Friday 29 July 2016

Implement custom iterator in Java

In this post, I am going to explain how to implement custom iterator and solve one interview question using iterator.

What is iterator?
Iterator is used to traverse the collection of elements. There is also a legacy class called Enumeration, it is also used to traverse collection of elements. Only difference is by using iterator you can remove an element while traversing, by using enumerator you can’t.

Let me brief the methods in iterator interface.
Method
Description
boolean hasNext()
Returns true if the iteration has more elements.
E next()
Returns the next element in the iteration.
default void remove()
Removes from the underlying collection the last element returned by this iterator. Java provides default implementation for this method. The default implementation throws an instance of UnsupportedOperationException and performs no other action.

Iterable interface
All the Java collections implementing Iterable interface, to return an iterator. Implementing this interface allows an object to be the target of the "foreach" statement. Following table summarizes the methods in Iterable interface.

Method
Description
Iterator<T> iterator()
Returns an iterator over a set of elements of type T.

Now lets come to the problem, I want to implement my own iterator. Suppose my collection has elements like 1, 2, 3, 4, 5, 6, 7, 8, 9. My iterator should traverse the elements at even positions like 1(is at 0th position), 3(is at 2nd position), 5, 7, 9.


I defined EvenList class like below.
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;

public class EvenList<T> implements Iterable<T> {
 private List<T> list;

 EvenList(List<T> list) {
  this.list = list;
 }

 public Iterator<T> iterator() {
  return new EvenIterator<T>();
 }

 @SuppressWarnings("hiding")
 private class EvenIterator<T> implements Iterator<T> {
  int size = list.size();
  int currentPointer = 0;

  public boolean hasNext() {
   return (currentPointer < size);
  }

  public T next() {
   if (!hasNext()) {
    throw new NoSuchElementException();
   }

   @SuppressWarnings("unchecked")
   T val = (T) list.get(currentPointer);
   currentPointer += 2;

   return val;
  }

 }

}

Total logic is in the next() method, here I am checking for an element in the collection using hasNext() method, it it returns false, I am throwing NoSuchElementException(). If element exists, then I am saving current element to a temporary variable and incrementing the currentPointer to 2.

import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

public class TestEvenList {
 public static void main(String args[]) {
  List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);

  EvenList<Integer> myList = new EvenList(list);

  Iterator<Integer> iter = myList.iterator();
  while (iter.hasNext()) {
   System.out.println(iter.next());
  }
 }
}


Run above program, you will get following output.

No comments:

Post a Comment