java – Collect successive pairs from a stream

Find 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()
);

Subsidence

[(0, 1), (1, 2), (2, 3), (3, 4)]

The function lead() accesses the next value in transversal order from the window.

Find successive triple / quadruple / n-tuples

A question in the comments asked for a more general solution, where one should not collect pairs but n-tuples (or possibly lists). So here’s 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()
);

Produce a list of lists

[[0, 1, 2], [1, 2, 3], [2, 3, 4]]

Without 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λ

Leave a comment