How can I get a java.lang.Iterable
from a collection like a Set
or a List
? Thanks!
A Collection is an Iterable . I know that the OP asked about it, but the assignment to Iterable is entirely unnecessary.
Iterable) is the root interface of the Java collection classes. The Collection interface extends Iterable interface, so all subtypes of Collection implement the Iterable interface. This interface stands to represent data-structures whose value can be traversed one by one. This is an important property.
Iterable is an object which can be looped over or iterated over with the help of a for loop. Objects like lists, tuples, sets, dictionaries, strings, etc. are called iterables. In short and simpler terms, iterable is anything that you can loop over.
To convert iterable to Collection, the iterable is first converted into spliterator. Then with the help of StreamSupport. stream(), the spliterator can be traversed and then collected with the help collect() into collection.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With