49

如何java.lang.Iterable从 aSet或 a 之类的集合中获取 a List?谢谢!

4

6 回答 6

83

A一个。Collection Iterable

所以你可以写:

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);
    }
}
于 2012-03-16T16:19:55.177 回答
10

我不清楚你需要什么,所以:

这会给你一个迭代器

SortedSet<String> sortedSet = new TreeSet<String>();
Iterator<String> iterator = sortedSet.iterator();

Sets 和 Lists 是 Iterables,这就是为什么您可以执行以下操作:

SortedSet<String> sortedSet = new TreeSet<String>();
Iterable<String> iterable = (Iterable<String>)sortedSet;
于 2012-03-16T16:20:06.757 回答
6

Iterable是 的超接口Collection,因此实现的任何类(例如SetListCollection也实现Iterable.

于 2012-03-16T16:21:05.913 回答
1

java.util.Collectionextends java.lang.Iterable,你不需要做任何事情,它已经是一个 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
于 2012-03-16T16:22:00.953 回答
1

SetList接口都扩展了Collection接口,而 Collection 接口本身扩展了Iterable接口。

于 2012-03-16T16:22:41.257 回答
0
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
}
于 2020-06-29T13:36:48.820 回答