Collection to Iterable
JavaCollectionsIterableJava Problem Overview
How can I get a java.lang.Iterable
from a collection like a Set
or a List
?
Thanks!
Java Solutions
Solution 1 - Java
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);
}
}
Solution 2 - Java
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;
Solution 3 - Java
Iterable
is a super interface to Collection
, so any class (such as Set
or List
) that implements Collection
also implements Iterable
.
Solution 4 - Java
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
Solution 5 - Java
Both Set and List interfaces extend the Collection interface, which itself extends the Iterable interface.
Solution 6 - Java
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
}