66

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

Amulya K Murthy
  • 130
  • 1
  • 2
  • 15
myborobudur
  • 4,385
  • 8
  • 40
  • 61

5 Answers5

100

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);
    }
}
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
assylias
  • 321,522
  • 82
  • 660
  • 783
12

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;
shujin
  • 181
  • 12
Tom
  • 4,096
  • 2
  • 24
  • 38
7

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

highlycaffeinated
  • 19,729
  • 9
  • 60
  • 91
2

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

raveturned
  • 2,637
  • 24
  • 30
1

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
Nathan Hughes
  • 94,330
  • 19
  • 181
  • 276