Different ways to iterate over Collections in Java Java 19.08.2016


The Java platform includes a variety of ways to iterate over a collection of objects, including new options based on features introduced in Java 8.

Following examples uses different techniques to iterate over Java collections.

I. Iterable.forEach method (Java 8)

This method can be called on any Iterable and takes one argument implementing the functional interface java.util.function.Consumer.

List<String> lst = Arrays.asList("WINTER", "SPRING", "SUMMER", "FALL");
lst.forEach(s -> System.out.println(s));

II. Java 'foreach' loop (Java 5)

The foreach loop syntax is:

for (Type var : Iterable) {
    // do something with "var"

Example for List

List<String> lst = Arrays.asList("WINTER", "SPRING", "SUMMER", "FALL");

for(String s : lst) {

Example for HashMap

HashMap animals = new HashMap();
animals.put("cat", "one");
animals.put("dog", "two");
animals.put("mouse", "one");

for (String key : animals.keySet()) {
   System.out.println("Key: " + key + " Value: " + animals.get(key));

III. java.util.Iterator (Java 2)

Using Iterator is still very popular way to iterate over collections, mainly due to addtional methods it provide to manipulate the collection elements.

List<String> lst = Arrays.asList("WINTER", "SPRING", "SUMMER", "FALL");
Iterator<String> itr = lst.iterator();

while(itr.hasNext()) {

IV. Traditional for loop

This is most appropriate when dealing with indexed collections such as list

for (init; test; change) {
    // do something

For example

List<String> lst = Arrays.asList("WINTER", "SPRING", "SUMMER", "FALL");

for(int i=0; i < lst.size(); i++) {