Collection to Iterable

myborobudur picture myborobudur · Mar 16, 2012 · Viewed 99.3k times · Source

How can I get a java.lang.Iterable from a collection like a Set or a List? Thanks!

Answer

assylias picture assylias · Mar 16, 2012

A Collection is an Iterable.

So you can write:

public static void main(String args[]) {
    List<String> list = new ArrayList<String>();
    list.add("a string");

    Iterable<String> iterable = list;
    for (String s : iterable) {
        System.out.println(s);
    }
}