在Java 8中,我们有类Stream<T>,它奇怪地有一个方法
Iterator<T> iterator()
所以你会期望它实现接口Iterable<T>,这需要这个方法,但事实并非如此。
当我想使用foreach循环遍历一个流时,我必须做如下的事情
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)) { ... }
我是不是遗漏了什么?
如果你不介意使用第三方库,cyclops-react定义了一个Stream,它实现了Stream和Iterable,并且也是可重玩的(解决了kennytm所描述的问题)。
Stream<String> stream = ReactiveSeq.of("hello","world")
.map(s->"prefix-"+s);
或:-
Iterable<String> stream = ReactiveSeq.of("hello","world")
.map(s->"prefix-"+s);
stream.forEach(System.out::println);
stream.forEach(System.out::println);
[披露我是cyclops-react的主要开发者]
如果你不介意使用第三方库,cyclops-react定义了一个Stream,它实现了Stream和Iterable,并且也是可重玩的(解决了kennytm所描述的问题)。
Stream<String> stream = ReactiveSeq.of("hello","world")
.map(s->"prefix-"+s);
或:-
Iterable<String> stream = ReactiveSeq.of("hello","world")
.map(s->"prefix-"+s);
stream.forEach(System.out::println);
stream.forEach(System.out::println);
[披露我是cyclops-react的主要开发者]