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.
You can do this with the Stream.reduce() method (I haven't seen any other answers using this technique).
In your case, I would write my custom IntFunction which keeps track of the last int passed and use that to map the original IntStream.
As others have observed, there is, due to the nature of the problem, some statefulness required.
I was faced with a similar problem, in which I wanted what was essentially the Oracle SQL function LEAD. My attempt to implement that is below.
Run a
for
loop that runs from 0 tolength-1
of your streamThe Java 8 streams library is primarily geared toward splitting streams into smaller chunks for parallel processing, so stateful pipeline stages are quite limited, and doing things like getting the index of the current stream element and accessing adjacent stream elements are not supported.
A typical way to solve these problems, with some limitations, of course, is to drive the stream by indexes and rely on having the values being processed in some random-access data structure like an ArrayList from which the elements can be retrieved. If the values were in
arrayList
, one could generate the pairs as requested by doing something like this:Of course the limitation is that the input cannot be an infinite stream. This pipeline can be run in parallel, though.
This is an interesting problem. Is my hybrid attempt below any good?
I believe it does not lend itself to parallel processing, and hence may be disqualified.