Java Tip #2: foreach with index (2)

Time for another Java Tip. Last time I described the problem of losing a loop counter when using the foreach loop. I mentioned, that I have two solutions for this problem. Here is the second one:

I created a class named It (short for “iterator”). It is a Iterable Iterator (funny, but true: Not all Iterators are Iterable in Java…) which allows you to wrap any collection and use it within a foreach loop. Moreover, it contains the method getIndex() which returns the current value of the loop counter. For quick creation, there is the it factory method which you should import statically.

Here is an example:

It<Foo> fooIt = it(fooList);
for (Foo foo : fooIt) {
  //for each foo in fooList...
  foo.doSomething();
  //if you need the current index:
  System.out.println(fooIt.getIndex());
}

You can also write similar iterators, like ReverseIterator for an iterator which begins with the last element and ends with the first one. Enjoy 🙂

Downloads: It, ReverseIterator

Leave a Reply

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