你能把一个流分成两个流吗?

编程入门 行业动态 更新时间:2024-10-21 19:41:10
本文介绍了你能把一个流分成两个流吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

更多推荐

你能把一个流分成两个流吗?

本文发布于:2023-11-26 00:37:42,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1631957.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:能把   两个

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!