myborobudur
myborobudur

Reputation: 4435

Collection to Iterable

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

Upvotes: 69

Views: 157950

Answers (5)

assylias
assylias

Reputation: 328568

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

Upvotes: 103

Tom
Tom

Reputation: 4180

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;

Upvotes: 12

Nathan Hughes
Nathan Hughes

Reputation: 96385

java.util.Collection extends java.lang.Iterable, you don't have to do anything, it already is an Iterable.

groovy:000> mylist = [1,2,3]
===> [1, 2, 3]
groovy:000> mylist.class
===> class java.util.ArrayList
groovy:000> mylist instanceof Iterable
===> true
groovy:000> def doStuffWithIterable(Iterable i) {
groovy:001>   def iterator = i.iterator()
groovy:002>   while (iterator.hasNext()) {
groovy:003>     println iterator.next()
groovy:004>   }
groovy:005> }
===> true
groovy:000> doStuffWithIterable(mylist)
1
2
3
===> null

Upvotes: 1

raveturned
raveturned

Reputation: 2677

Both Set and List interfaces extend the Collection interface, which itself extends the Iterable interface.

Upvotes: 2

highlycaffeinated
highlycaffeinated

Reputation: 19867

Iterable is a super interface to Collection, so any class (such as Set or List) that implements Collection also implements Iterable.

Upvotes: 7

Related Questions