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

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

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

更多推荐

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

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

发布评论

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

>www.elefans.com

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