java streamcopy,我可以在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?

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

解决方案

It is not possible in general.

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

A. Keep everything in a collection, say a List<>

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.

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

This itertool may require significant auxiliary storage (depending on how much temporary data needs to be stored). In general, if one iterator uses most or all of the data before another iterator starts, it is faster to use list() instead of tee().

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]

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]

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).

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值