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
Release: 2024-11-30 06:45:15
Original
380 people have browsed it

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) }
Copy after login

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);
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template