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.
My StreamEx library which extends standard streams provides a
pairMap
method for all stream types. For primitive streams it does not change the stream type, but can be used to make some calculations. Most common usage is to calculate differences:For object stream you can create any other object type. My library does not provide any new user-visible data structures like
Pair
(that's the part of library concept). However if you have your ownPair
class and want to use it, you can do the following:Or if you already have some
Stream
:This functionality is implemented using custom spliterator. It has quite low overhead and can parallelize nicely. Of course it works with any stream source, not just random access list/array like many other solutions. In many tests it performs really well. Here's a JMH benchmark where we find all input values preceding a larger value using different approaches (see this question).
We can use RxJava (very powerful reactive extension library)
You can achieve that by using a bounded queue to store elements which flows through the stream (which is basing on the idea which I described in detail here: Is it possible to get next element in the Stream?)
Belows example first defines instance of BoundedQueue class which will store elements going through the stream (if you don't like idea of extending the LinkedList, refer to link mentioned above for alternative and more generic approach). Later you just combine two subsequent elements into instance of Pair:
I agree with @aepurniet but instead map you have to use mapToObj
The proton-pack library provides the windowed functionnality. Given a Pair class and a Stream, you can do it like this:
Now the
pairs
stream contains:Finding successive pairs
If you're willing to use a third party library and don't need parallelism, then jOOλ offers SQL-style window functions as follows
Yielding
The
lead()
function accesses the next value in traversal order from the window.Finding successive triples / quadruples / n-tuples
A question in the comments was asking for a more general solution, where not pairs but n-tuples (or possibly lists) should be collected. Here's thus an alternative approach:
Yielding a list of lists
Without the
filter(w -> w.count() == n)
, the result would beDisclaimer: I work for the company behind jOOλ