Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Collection to Iterable

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

like image 574
myborobudur Avatar asked Mar 16 '12 16:03

myborobudur


People also ask

Is a Collection an iterable?

A Collection is an Iterable . I know that the OP asked about it, but the assignment to Iterable is entirely unnecessary.

Why do collections extend Iterable?

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.

What is the meaning of iterable?

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.

How do I convert iterable to collections?

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.


2 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);     } } 
like image 140
assylias Avatar answered Oct 02 '22 01:10

assylias


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; 
like image 33
Tom Avatar answered Oct 02 '22 00:10

Tom