Why does Streamlt;Tgt; not implement Iterablelt;Tgt;?(为什么 Streamlt;Tgt;不实现Iterablelt;Tgt;?)
问题描述
在 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)) { ... }
我错过了什么吗?
推荐答案
人们已经问过同样的问题 在邮件列表中 ☺.主要原因是Iterable也有可重迭代的语义,而Stream没有.
People have already 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
Iterableimplies reusability, whereasStreamis something that can only be used once — more like anIterator.
如果 Stream 扩展了 Iterable 则现有代码在收到抛出 Exception 的 Iterable 时可能会感到惊讶这他们第二次 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>?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么 Stream<T>不实现Iterable<T>?
基础教程推荐
- RabbitMQ:消息保持“未确认"; 2022-01-01
- 存储 20 位数字的数据类型 2022-01-01
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
- 使用堆栈算法进行括号/括号匹配 2022-01-01
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
- Struts2 URL 无法访问 2022-01-01
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
- 修改 void 函数的输入参数,然后读取 2022-01-01
- 如何对 Java Hashmap 中的值求和 2022-01-01
