Home >Java >javaTutorial >How to Efficiently Create Successive Pairs from a Data Stream in Java?

How to Efficiently Create Successive Pairs from a Data Stream in Java?

Barbara Streisand
Barbara StreisandOriginal
2024-11-30 06:45:15337browse

How to Efficiently Create Successive Pairs from a Data Stream in Java?

Efficiently Constructing Successive Pairs from a Stream

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn