有没有办法重用一个流? [英] Is there any way to reuse a Stream?
本文介绍了有没有办法重用一个流?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在学习新的Java 8功能,在尝试使用流( java.util.stream.Stream
)和收集器时,我意识到流可以' t两次使用。
I'm learning the new Java 8 features, and while experimenting with streams (java.util.stream.Stream
) and collectors, I realized that a stream can't be used twice.
有没有办法重复使用它?
Is there any way to reuse it?
推荐答案
如果想要重用流,可以将流表达式包装在供应商中并调用 myStreamSupplier.get()
只要你想要一个新的。例如:
If you want to have the effect of reusing a stream, you might wrap the stream expression in a Supplier and call myStreamSupplier.get()
whenever you want a fresh one. For example:
Supplier<Stream<String>> sup = () -> someList.stream();
List<String> nonEmptyStrings = sup.get().filter(s -> !s.isEmpty()).collect(Collectors.toList());
Set<String> uniqueStrings = sup.get().collect(Collectors.toSet());
这篇关于有没有办法重用一个流?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文