How can I get a java.lang.Iterable from a collection like a Set or a List?
Thanks!
6 Answers
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;
Iterable is a super interface to Collection, so any class (such as Set or List) that implements Collection also implements Iterable.
Both Set and List interfaces extend the Collection interface, which itself extends the Iterable interface.
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
public static void main(String args[]) {
List<String> list = new ArrayList<String>();
list.add("a string");
Collection<String> collection = list;
Iterable<String> iterable = collections;
for (String s : iterable) {
System.out.println(s);
}
list -> collection->iterable
}