Use for each liberally

The for-each loop is used with both collections and arrays. It's intended to simplify the most common form of iteration, where the iterator or index is used solely for iteration, and not for any other kind of operation, such as removing or editing an item in the collection or array. When there is a choice, the for-each loop should be preferred over the for loop, since it increases legibility.


Here are some examples of the for-each loop.

import java.util.*;
import java.math.BigDecimal;

public final class ForEachExamples {

  public static void main(String... aArgs){
    List<Number> numbers = new ArrayList<>();
    numbers.add(new Integer(42));
    numbers.add(new Integer(-30));
    numbers.add(new BigDecimal("654.2"));

    //typical for-each loop
    //processes each item, without changing the collection or array.
    for (Number number : numbers){

    //use with an array
    String[] names = {"Ethan Hawke", "Julie Delpy"};
    for(String name : names){
      log("Name : " + name);

    //removal of items requires an explicit iterator,
    //so you can't use a for-each loop in this case
    Collection<String> words = new ArrayList<>();
    words.add("Il ne lui faut que deux choses: ");
    words.add("- Alfred de Vigny.");
    for(Iterator<String> iter = words.iterator(); iter.hasNext();){
      if ( == 4){
    log("Edited words: " + words.toString());

    //if used with a non-parameterized type (not recommended), 
    //then Object must be used, along with a cast
    Collection stuff = new ArrayList();
    for (Object thing : stuff){
      String item = (String)thing;
      log("Thing : " + item);

  private static void log(Object aThing){

See Also :
Iterate without an index
Ways of iterating
Modernize old code