Home >Java >javaTutorial >How to Efficiently Create Successive Pairs from a Data Stream in Java?
Given a stream of primitive or object values, the task arises to transform it into a stream of pairs, where each pair comprises two successive elements from the original stream. For instance, given the stream {0, 1, 2, 3, 4}, the desired output would be:
{ new Pair(0, 1), new Pair(1, 2), new Pair(2, 3), new Pair(3, 4) }
Analysis
The Java 8 streams library excels in dividing streams into smaller portions for parallel processing. However, it offers limited support for stateful pipeline stages, making it challenging to access adjacent stream elements and obtain the index of the current element.
Solution
To overcome these limitations, we can leverage an indexed approach whereby we drive the stream using indexes. This requires the values to be stored in a random-access data structure like an ArrayList, from which elements can be conveniently retrieved. With the values in an ArrayList, we can construct the pairs as follows:
IntStream.range(1, arrayList.size()) .mapToObj(i -> new Pair(arrayList.get(i-1), arrayList.get(i))) .forEach(System.out::println);
Note that this approach has the constraint of requiring the input to be a finite stream. However, the pipeline can be executed in parallel.
The above is the detailed content of How to Efficiently Create Successive Pairs from a Data Stream in Java?. For more information, please follow other related articles on the PHP Chinese website!