Use for statement with Iterable object in Java

Description

The following code shows how to use for statement with Iterable object.

It can iterate over a Collection without the need to call the iterator method. The syntax is


for (Type identifier : expression) {
         statement (s)
}

In which expression must be an Iterable.

Example


/*from   w  w w .j  a  va2s  . c  om*/

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

public class Main {
  public static void main(String[] args) {
    List list = Arrays.asList("A", "B", "C", "D");

    for (Object object : list) {
      System.out.println(object);
    }

  }
}

The code above generates the following result.





















Home »
  Java Tutorial »
    Java Collection »




Java ArrayList
Java Collection
Java Comparable
Java Comparator
Java HashMap
Java HashSet
Java Iterator
Java LinkedHashMap
Java LinkedHashSet
Java LinkedList
Java List
Java ListIterator
Java Map
Queue
Java Set
Stack
Java TreeMap
TreeSet