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.

Example

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... args){
    List<Number> numbers = new ArrayList<>();
    numbers.add(42);
    numbers.add(-30);
    numbers.add(new BigDecimal("654.2"));

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

    //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("le");
    words.add("pain");
    words.add("et");
    words.add("le");
    words.add("temps.");
    words.add("- Alfred de Vigny.");
    for(Iterator<String> iter = words.iterator(); iter.hasNext();){
      if (iter.next().length() == 4){
        iter.remove();
      }
    }
    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();
    stuff.add("blah");
    for (Object thing : stuff){
      String item = (String)thing;
      log("Thing : " + item);
    }
  }

  // PRIVATE
  private static void log(Object aThing){
    System.out.println(aThing);
  }
}
 

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