我有一个由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 s;这没有意义 - 如何在不需要同时生成另一个的情况下迭代一个?一个流只能运行一次。
Not exactly. You can't get two Streams 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));更多推荐
你能将一个流分成两个流吗?
发布评论