Collection to Iterable

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


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);
    }
}

It's not clear to me what you need, so:

this gets you an Iterator

SortedSet<String> sortedSet = new TreeSet<String>();
Iterator<String> iterator = sortedSet.iterator();

Sets and Lists are Iterables, that's why you can do the following:

SortedSet<String> sortedSet = new TreeSet<String>();
Iterable<String> iterable = (Iterable<String>)sortedSet;