Java Programming Tutorials

Java programming tutorials with many code examples!

Java foreach

Problem:

How to use foreach loop (enhanced for) that came with Java 5?

Solution:

This short examples explain everything:

package com.farenda.solved;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class JavaSolved {

    private static int[] numbers = { 1, 2, 3 };
    private static List<String> objects
        = Arrays.asList(new String[] {"a", "b", "c"});
    private static List emptyList = Collections.emptyList();

    public static void main(String[] args) {
        // With arrays it uses "index" and array's length field to iterate:
        System.out.println("Iterating array: " + numbers);
        for (int x : numbers) {
            System.out.println(x);
        }

        // It works with any class implementing java.lang.Iterable,
        // so Lists, Sets, Maps, etc.
        // Underneath it uses an iterator:
        System.out.println("Iterating over Iterable: " + objects);
        for (String s : objects) {
            System.out.println(s);
        }

        // When Iterable or array is empty Java for-each daos nothing:
        System.out.println("Iterating over an empty Iterable: " + emptyList);
        for (Object o : emptyList) {
            System.out.println(o);
        }

        // For-each doesn't check if Array or Iterable is null and will
        // throw NullPointerException when given one!
    }
}

Using Java for-each loop doesn’t work when you want to modify (e.g. remove matching element) Iterable over which you are iterating. In such case you will need to use simple iterator.

Result:

Let’s compile and run the examples:

$> javac src/com/farenda/solved/*.java -d out
$> java -cp out com.farenda.solved.JavaSolved
Iterating array: [I@659e0bfd
1
2
3
Iterating over Iterable: [a, b, c]
a
b
c
Iterating over an empty Iterable: []
Share with the World!