Good programming practices

How to iterate a list with index

April 10th, 2012

There is many ways to iterate a list or other collection in Java. Sometimes it is useful to have also current index, especially when it is a List, where the elements order matters. It can be achieved be several ways. Lets look at the example:

  1. public static void main(String[] args) {
  2. List<String> list = Arrays.asList("zero", "one", "two", "three");
  3. standardLoop(list);
  4. forEachWithLocalVariable(list);
  5. listIterator(list);
  6. }

All the 3 methods make the same output:

0 zero
1 one
2 two
3 three
  1. private static void standardLoop(List<String> list) {
  2. System.out.println("#1. Standard for loop");
  3. for (int i = 0, n = list.size(); i < n; i++) {
  4. System.out.println(i + " " + list.get(i));
  5. }
  6. }
First method is short, but you need to use 1 or 2 local variables (depending if used n = list.size()).

  1. private static void forEachWithLocalVariable(List<String> list) {
  2. System.out.println("#2. For-each with local variable");
  3. int i = 0;
  4. for (String element : list) {
  5. System.out.println(i + " " + element);
  6. i++;
  7. }
  8. }
This method is long and local variable outside of the loop. If you would use several such loops in one block of code, you have to remember to clear value of the variable (i = 0) or use different name.

  1. private static void listIterator(List<String> list) {
  2. System.out.println("#3. List iterator");
  3. for (ListIterator<String> it = list.listIterator(); it.hasNext();) {
  4. System.out.println(it.nextIndex() + " " +;
  5. }
  6. }
Here only iterator is local variable. For this case you have to remember that each time next() is called, it returns other element. If you want use the element many times inside the loop, assign next() to local variable.

From this 3 examples, you should avoid the second. It’s messy and error prone when this code repeats in the same block. Third example is probably what you should use. First case is good when more control of the list is needed (e.g. access to other elements of the list at the same time).

Leave a Response

You must be logged in to post a comment.