Iterator – Java

If you have a collection in some object oriented language (e.g., Java) you might be interested in traversing it. By traversing I mean visiting each and every one of the members in the collection in some specific order (e.g., front to back, back to front). Many collections already come with an Iterator. Some do not. In particular you may develop an object and wish to traverse it from first to last. In that case you could develop an Iterator.

If you wish to learn more about collections and iterators, I would recommend using a reference book (e.g., Algorithms fourth edition by Robert Sedgewick and Kevin Wayne) or perform a search on the Internet.

In this example let’s say we need to iterate on a collection of integers. You can always extend this example to use any type object.

Let’s take a look at the following screen capture from my Eclipse IDE console:

// contents of a stack of integers:

<<< i: 33

<<< i: 71

<<< i: 87

<<< i: 35

<<< i: 59

<<< i: 16

<<< i: 84

// stack traversed in order:

<<< e: 33

<<< e: 71

<<< e: 87

<<< e: 35

<<< e: 59

<<< e: 16

<<< e: 84

// first (top) element in the stack:

<<< firstElement: 33

// last element in the stack:

<<<  lastElement: 84

// stack traversed in reverse order:

<<< r: 84

<<< r: 16

<<< r: 59

<<< r: 35

<<< r: 87

<<< r: 71

<<< r: 33

The first list of numbers (i) shows the contents of a stack we created and populated with some random integers. The second list of the same numbers (e) in the same order is achieved using an Iterator through the stack. The first (top) and last elements in the stack are displayed. The final list of the same random numbers (r) in reverse order is displayed.

Following is the test code that produced the previous console output:

package john.iterator;

import java.util.Iterator;

import java.util.Random;

import java.util.Stack;

public class Solution {

public static void main(String[] args) {

// **** ****

final int TOTAL_ENTRIES = 7;

final int MAX_VALUE = 100;

// **** ****

Random rand = new Random(System.currentTimeMillis());

// **** instantiate a stack and populate it with unique random values ****

Stack<Integer> stack = new Stack<Integer>();

for (int i = 0; i < TOTAL_ENTRIES; i++) {

// **** make sure the number is unique ****

int val = 1 + rand.nextInt(MAX_VALUE);

while (stack.contains(val)){

val = 1 + rand.nextInt(MAX_VALUE);

}

// **** push the number into the stack ****

stack.push(val);

}

// **** loop through the contents of the stack ****

for (int i : stack) {

System.out.println(“<<< i: ” + i);

}

System.out.println();

// **** iterate through the stack ****

Iterator<Integer> iter = stack.iterator();

while (iter.hasNext()) {

int e = iter.next();

System.out.println(“<<< e: ” + e);

}

System.out.println();

// **** ****

System.out.println(“<<< firstElement: ” + stack.firstElement());

System.out.println(“<<<  lastElement: ” + stack.lastElement());

System.out.println();

// **** iterate in reverse order through the contents of the stack ****

ReverseStackIterator riter = new ReverseStackIterator(stack);

while (riter.hasNext()) {

System.out.println(“<<< r: ” + riter.next());

}

}

}

To keep it short the number of entries and range are controlled. To make sure we do not have duplicates that might cause confusion, the numbers pushed into the stack are random unique integers in the specified range.

In the first display loop we use an index into the stack. The second loop uses the Iterator provided by the stack collection. The first and last entries in the stack are displayed to make sure we know where the top element is displayed.

We then instantiate and use a reverse order Iterator and display the contents of the stack in reverse order.

Following is the code for the ReverseStackIterator class:

package john.iterator;

import java.util.Iterator;

import java.util.Stack;

public class ReverseStackIterator implements Iterator<Integer> {

// **** members ****

Stack<Integer> stack;

int index;

// **** constructor ****

public ReverseStackIterator(Stack<Integer> stack) {

this.stack = stack;

index = stack.size() – 1;

}

// **** required methods ****

@Override

public boolean hasNext() {

return (index >= 0);

}

@Override

public Integer next() {

return stack.elementAt(index–);

}

}

We require a constructor and the implementation of the hasNext() and next() methods because the class implements the Iterator interface.

If you have comments or questions regarding this or any other post in this blog, please do not hesitate and send me a message. I will not use your name unless you explicitly allow me to do so.

John

john.canessa@gmail.com

Follow me on Twitter: @john_canessa

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.