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
Collection to Iterable
提问by myborobudur
How can I get a java.lang.Iterable
from a collection like a Set
or 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
Iterable
is a super interface to Collection
, so any class (such as Set
or List
) that implements Collection
also implements Iterable
.
Iterable
是 的超级接口Collection
,因此任何实现的类(例如Set
或List
)Collection
也实现Iterable
。
回答by Nathan Hughes
java.util.Collection
extends java.lang.Iterable
, you don't have to do anything, it already is an Iterable.
java.util.Collection
extends 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