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
System.out.println(
Seq.of(0, 1, 2, 3, 4)
.window()
.filter(w -> w.lead().isPresent())
.map(w -> tuple(w.value(), w.lead().get())) // alternatively, use your new Pair() class
.toList()
);
Yielding
[(0, 1), (1, 2), (2, 3), (3, 4)]
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:
int n = 3;
System.out.println(
Seq.of(0, 1, 2, 3, 4)
.window(0, n - 1)
.filter(w -> w.count() == n)
.map(w -> w.window().toList())
.toList()
);
Yielding a list of lists
[[0, 1, 2], [1, 2, 3], [2, 3, 4]]
Without the filter(w -> w.count() == n)
, the result would be
[[0, 1, 2], [1, 2, 3], [2, 3, 4], [3, 4], [4]]
Disclaimer: I work for the company behind jOOλ
list.stream().map(i -> new Pair(i, i+1));
– aepurnietMap.Entry
as a Pair class. (Granted, some might consider that a hack, but using a built-in class is handy.) – Basil Bourque