为什么Stream< T>没有实现Iterable< T>? [英] Why does Stream<T> not implement Iterable<T>?
问题描述
在Java 8中,我们有一个类 Stream< T> ,奇怪地有一个方法
In Java 8 we have the class Stream<T>, which curiously have a method
Iterator<T> iterator()
所以你希望它实现接口 Iterable< T> ,这完全需要这种方法,但事实并非如此。
So you would expect it to implement interface Iterable<T>, which requires exactly this method, but that's not the case.
当我想使用foreach循环遍历Stream时,我必须执行类似
When I want to iterate over a Stream using a foreach loop, I have to do something like
public static Iterable<T> getIterable(Stream<T> s) {
return new Iterable<T> {
@Override
public Iterator<T> iterator() {
return s.iterator();
}
};
}
for (T element : getIterable(s)) { ... }
我在这里遗漏了什么吗?
Am I missing something here?
推荐答案
已经有人问过同样的邮件列表☺。主要原因是Iterable也有一个可重复的语义,而Stream则没有。
There are already people asked the same on the mailing list ☺. The main reason is Iterable also has a re-iterable semantic, while Stream is not.
我认为主要原因是
Iterable
意味着可重用性,而Stream
只能使用一次 - 更像是Iterator
。
I think the main reason is that
Iterable
implies reusability, whereasStream
is something that can only be used once — more like anIterator
.
如果流
扩展可转换
然后现有的代码可能会收到 Iterable
,它会在第二次抛出$ code> Exception
时感到惊讶执行 for(element:iterable)
。
If Stream
extended Iterable
then existing code might be surprised when it receives an Iterable
that throws an Exception
the
second time they do for (element : iterable)
.
这篇关于为什么Stream< T>没有实现Iterable< T>?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!