你能将一个流分成两个流吗? [英] Can you split a stream into two streams?

查看:119
本文介绍了你能将一个流分成两个流吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个由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));

这篇关于你能将一个流分成两个流吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆