我可以在Java 8中复制Stream吗? [英] Can I duplicate a Stream in Java 8?

查看:332
本文介绍了我可以在Java 8中复制Stream吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有时我想对流执行一组操作,然后以不同的方式处理生成的流与其他操作。

Sometimes I want to perform a set of operations on a stream, and then process the resulting stream two different ways with other operations.

我可以在没有流的情况下执行此操作两次指定常见的初始操作?

Can I do this without having to specify the common initial operations twice?

例如,我希望 dup()方法,例如存在以下:

For example, I am hoping a dup() method such as the following exists:

Stream [] desired_streams = IntStream.range(1, 100).filter(n -> n % 2 == 0).dup();
Stream stream14 = desired_streams[0].filter(n -> n % 7 == 0); // multiples of 14
Stream stream10 = desired_streams[1].filter(n -> n % 5 == 0); // multiples of 10


推荐答案

一般情况下不可能。

如果要复制输入流或输入迭代器,您有两种选择:

If you want to duplicate an input stream, or input iterator, you have two options:

假设您将流复制到两个流中 s1 s2 。如果您在 s1 n2 元素中有高级 n1 元素使用 s2 ,您必须在内存中保留 | n2 - n1 | 元素,以保持同步。如果你的流是无限的,那么所需的存储可能没有上限。

Suppose you duplicate a stream into two streams s1 and s2. If you have advanced n1 elements in s1 and n2 elements with s2, you must keep |n2 - n1| elements in memory, just to keep pace. If your stream is infinite, there may be no upper bound for the storage required.

看一下Python的 tee() 查看需要的内容:

Take a look at Python's tee() to see what it takes:


此itertool可能需要大量辅助存储(取决于需要存储多少临时数据)。通常,如果一个迭代器在另一个迭代器启动之前使用大部分或全部数据,则使用 list()代替 tee()会更快



B.如果可能:复制创建元素的生成器的状态



要使此选项起作用,您可能需要访问流的内部工作方式。换句话说,生成器 - 创建元素的部分 - 应该首先支持复制。 [OP:请参阅此 精彩回答 ,作为如何为此做到这一点的示例问题中的示例]

B. When possible: Copy the state of the generator that creates the elements

For this option to work, you'll probably need access to the inner workings of the stream. In other words, the generator - the part that creates the elements - should support copying in the first place. [OP: See this great answer, as an example of how this can be done for the example in the question]

它不适用于用户的输入,因为您必须复制整个外部世界的状态。 Java的 Stream 不支持复制,因为它设计得尽可能通用,专门用于处理文件,网络,键盘,传感器,随机性等。[OP:Another示例是按需读取温度传感器的流。如果不存储读数的副本就不能复制]

It will not work on input from the user, since you'll have to copy the state of the whole "outside world". Java's Stream do not support copying, since it is designed to be as general as possible, specifically to work with files, network, keyboard, sensors, randomness etc. [OP: Another example is a stream that reads a temperature sensor on demand. It cannot be duplicated without storing a copy of the readings]

这不仅仅是Java的情况;这是一般规则。您可以看到 std :: istream 中的c> 仅支持移动语义,而不支持复制语义(复制构造函数(已删除)),因此(以及其他)。

This is not only the case in Java; this is a general rule. You can see that std::istream in C++ only supports move semantics, not copy semantics ("copy constructor (deleted)"), for this reason (and others).

这篇关于我可以在Java 8中复制Stream吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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