Java 可迭代的集合

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9740830/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-16 06:59:41  来源:igfitidea点击:

Collection to Iterable

javacollectionsiterable

提问by myborobudur

How can I get a java.lang.Iterablefrom a collection like a Setor a List? Thanks!

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

采纳答案by assylias

A Collection isan 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);
    }
}

回答by Tom

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;

回答by highlycaffeinated

Iterableis a super interface to Collection, so any class (such as Setor List) that implements Collectionalso implements Iterable.

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

回答by Nathan Hughes

java.util.Collectionextends java.lang.Iterable, you don't have to do anything, it already is an Iterable.

java.util.Collectionextends java.lang.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

回答by raveturned

Both Setand Listinterfaces extend the Collectioninterface, which itself extends the Iterableinterface.

这两种设置目录接口扩展接口,其本身扩展了可迭代接口。