How can I get a java.lang.Iterable
from a collection like a Set
or a List
?
Thanks!
Asked
Active
Viewed 1.4e+01k times
66

Amulya K Murthy
- 130
- 1
- 2
- 15

myborobudur
- 4,385
- 8
- 40
- 61
-
3Do you mean `Iterator` instead of `Iterable`? A `List` implements the `Iterable` interface. An `Iterator` allows you to iterate through a `List`'s elements. – nwinkler Mar 16 '12 at 16:21
-
My interface is actually SortedSet – myborobudur Mar 16 '12 at 17:39
5 Answers
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
-
2I know that the OP asked about it, but the assignment to `Iterable` is entirely unnecessary. – nwinkler Mar 16 '12 at 16:28
-
1
-
1
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;
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