Given a stream such as { 0, 1, 2, 3, 4 }
,
how can I most elegantly transform it into given form:
{ new Pair(0, 1), new Pair(1, 2), new Pair(2, 3), new Pair(3, 4) }
(assuming, of course, I've defined class Pair)?
Edit: This isn't strictly about ints or primitive streams. The answer should be general for a stream of any type.
This is not elegant, it's a hackish solution, but works for infinite streams
Now you can limit your stream to the length you want
P.S. I hope there is better solution, something like clojure
(partition 2 1 stream)
The operation is essentially stateful so not really what streams are meant to solve - see the "Stateless Behaviors" section in the javadoc:
One solution here is to introduce state in your stream through an external counter, although it will only work with a sequential stream.
You can do this in cyclops-react (I contribute to this library), using the sliding operator.
Or
Assuming the Pair constructor can accept a Collection with 2 elements.
If you wanted to group by 4, and increment by 2 that is also supported.
Equivalant static methods for creating a sliding view over java.util.stream.Stream are also provided in cyclops-streams StreamUtils class.
Note :- for single-threaded operation ReactiveSeq would be more appropriate. LazyFutureStream extends ReactiveSeq but is primarily geared for concurrent / parallel use (it is a Stream of Futures).
LazyFutureStream extends ReactiveSeq which extends Seq from the awesome jOOλ (which extends java.util.stream.Stream), so the solutions Lukas' presents would also work with either Stream type. For anyone interested the primary differences between the window / sliding operators are the obvious relative power / complexity trade off and suitability for use with infinite streams (sliding doesn't consume the stream, but buffers as it flows).
I've implemented a spliterator wrapper which takes every
n
elementsT
from the original spliterator and producesList<T>
:Following method may be used to create a consecutive stream:
Sample usage:
An elegant solution would be to use zip. Something like:
This is pretty concise and elegant, however it uses a list as an input. An infinite stream source cannot be processed this way.
Another (lot more troublesome) issue is that zip together with the entire Streams class has been lately removed from the API. The above code only works with b95 or older releases. So with the latest JDK I would say there is no elegant FP style solution and right now we can just hope that in some way zip will be reintroduced to the API.
For calculating successive differences in the time (x-values) of a time-series, I use the
stream
'scollect(...)
method:Where the DifferenceCollector is something like this:
You could probably modify this to suit your needs.