Comment puis-je obtenir un java.lang.Iterable
d'une collection comme un Set
ou un List
?
Merci!
Réponses
Trop de publicités?Un Collection
est un Iterable
.
Vous pouvez donc écrire :
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);
}
}
Tom
Points
2694
Ce dont vous avez besoin n'est pas clair pour moi, alors :
cela vous donne un itérateur
SortedSet<String> sortedSet = new TreeSet<String>();
Iterator<String> iterator = sortedSet.iterator();
Les ensembles et les listes sont des itérables, c'est pourquoi vous pouvez effectuer les opérations suivantes :
SortedSet<String> sortedSet = new TreeSet<String>();
Iterable<String> iterable = (Iterable<String>)sortedSet;
highlycaffeinated
Points
11645
raveturned
Points
1283
Les interfaces Set et List étendent l' interface Collection , qui elle-même étend l'interface Iterable.
Nathan Hughes
Points
30377
java.util.Collection
étend java.lang.Iterable
, vous n'avez rien à faire, c'est déjà un 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