你能把一个流分成两个流吗? [英] Can you split a stream into two streams?
问题描述
我有一个由 Java 8 流表示的数据集:
I have a data set represented by a Java 8 stream:
Stream<T> stream = ...;
我可以看到如何过滤它以获得随机子集 - 例如
I can see how to filter it to get a random subset - for example
Random r = new Random();
PrimitiveIterator.OfInt coin = r.ints(0, 2).iterator();
Stream<T> heads = stream.filter((x) -> (coin.nextInt() == 0));
我还可以看到如何减少此流以获取例如代表数据集的两个随机一半的两个列表,然后将它们转换回流.但是,有没有一种直接的方法可以从初始流生成两个流?类似的东西
I can also see how I could reduce this stream to get, for example, two lists representing two random halves of the data set, and then turn those back into streams. But, is there a direct way to generate two streams from the initial one? Something like
(heads, tails) = stream.[some kind of split based on filter]
感谢您的任何见解.
推荐答案
不完全是.你不能从一个Stream
中得到两个;这没有意义——你将如何迭代一个而不需要同时生成另一个?一个流只能操作一次.
Not exactly. You can't get two Stream
s out of one; this doesn't make sense -- how would you iterate over one without needing to generate the other at the same time? A stream can only be operated over once.
但是,如果您想将它们转储到列表或其他内容中,您可以这样做
However, if you want to dump them into a list or something, you could do
stream.forEach((x) -> ((x == 0) ? heads : tails).add(x));
这篇关于你能把一个流分成两个流吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!