grokking hard

code smarter, not harder

How to iterate over a Collection in Java?

Posted at — 2016-May-26

Traditional way

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
List<Integer> numbers = ...

for (int i = 0; i < numbers.length(); i++) {
  if (i % 2 == 0) {
    Integer value = numbers.get(i);
    if (value % 2 == 0) {
      // do something to value
    }
  }
} 

Pros:

Cons:

Use:

The Iterator way

In Java, Array and Collection all implement Iterable which returns an Iterator. Suppose I want to find and remove a value:

1
2
3
4
5
6
7
8
List<Integer> numbers = ...

for (Iterator<Integer> it = numbers.iterator(); it.hasNext();) { 
  Integer value = it.next();
  if (value % 2 == 0) { 
    it.remove();
  }
} 

If you need to know the index, use ListIterator (only work with List):

1
2
3
4
5
6
7
8
9
List<Integer> numbers = ...

for (ListIterator<Integer> it = numbers.listIterator(); it.hasNext();) {
  Integer index = it.nextIndex();
  Integer value = it.next();
  if (index % 2 == 0 && value % 2 == 0) {
    it.remove();
  }
} 

Pros:

Cons:

The Enhanced for way

This is the most recommended way since Java 5 if you just need to iterate over a Collection without the need to access to the index.

1
2
3
4
5
6
7
8
List<Integer> numbers = ...

// read as "for each number in numbers"
for (Integer number : numbers) {
  if (number % 2 == 0) {
    // do something with number
  }
} 

TIP: To iterate over an entire java.util.Map, please use this:

1
2
3
4
5
Map<String, Object> cache = ...

for (Map.Entry<String, Object> entry : cache.entrySet()) {
  doSomeThingTo(entry.getKey(), entry.getValue());
}

Pros:

Cons:

The Java 8 way (or the function way or the lambda way)

In Java 8, Stream API has been introduce which makes it very easy to iterate and do somthing no elements of a Collection.

1
2
3
4
5
6
7
8
9
List<Integer> numbers = ...

numbers.stream()
  .filter(number -> numbers % 2 == 0)
  .forEach(number -> doSomething(number));

// or simply

numbers.forEach(number -> doSomething(number)); 

Pros:

Cons: