Java Language Using Iterable in for loop

Download Java Language for free

Example

Classes implementing Iterable<> interface can be used in for loops. This is actually only syntactic sugar for getting an iterator from the object and using it to get all elements sequentially; it makes code clearer, faster to write end less error-prone.

public class UsingIterable {

    public static void main(String[] args) {
        List<Integer> intList = Arrays.asList(1,2,3,4,5,6,7);
        
        // List extends Collection, Collection extends Iterable
        Iterable<Integer> iterable = intList;
        
        // foreach-like loop
        for (Integer i: iterable) {
            System.out.println(i);
        }
        
        // pre java 5 way of iterating loops
        for(Iterator<Integer> i = iterable.iterator(); i.hasNext(); ) {
            Integer item = i.next();
            System.out.println(item);
        }
    }
}
Using the raw iterator