gpt4 book ai didi

java - 为什么 Stream 没有实现 Iterable

转载 作者:bug小助手 更新时间:2023-10-28 10:40:10 25 4
gpt4 key购买 nike

在 Java 8 中,我们有类 Stream<T> , 奇怪的是有一个方法

Iterator<T> iterator()

所以你会期望它实现接口(interface) Iterable<T> ,这正是需要这种方法,但事实并非如此。

当我想使用 foreach 循环遍历 Stream 时,我必须执行类似的操作

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)) { ... }

我错过了什么吗?

最佳答案

人们已经问过同样的问题on the mailing list ☺。主要原因是Iterable也有可重迭代的语义,而Stream没有。

I think the main reason is that Iterable implies reusability, whereas Stream is something that can only be used once — more like an Iterator.

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).

关于java - 为什么 Stream<T> 没有实现 Iterable<T>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20129762/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com