Home >Java >javaTutorial >How Can I Efficiently Generate Consecutive Pairs from a Java Stream?

How Can I Efficiently Generate Consecutive Pairs from a Java Stream?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-29 08:19:10190browse

How Can I Efficiently Generate Consecutive Pairs from a Java Stream?

Collecting Consecutive Pairs from Streams

Generating consecutive pairs from a stream of elements is a common task in programming. Consider the task of converting a simple stream like { 0, 1, 2, 3, 4 } into a stream of pairs as follows: { new Pair(0, 1), new Pair(1, 2), new Pair(2, 3), new Pair(3, 4) }.

In Java 8, streams are primarily designed for splitting data into smaller chunks for parallel processing. As a result, stateful pipeline stages are limited, and operations like accessing adjacent stream elements are not directly supported.

One approach to address this limitation is to use the stream indices by relying on a random-access data structure like an ArrayList. For example, if the stream elements are stored in an ArrayList, we can generate the desired pairs as follows:

IntStream.range(1, arrayList.size())
             .mapToObj(i -> new Pair(arrayList.get(i-1), arrayList.get(i)))
             .forEach(System.out::println);

This solution has a limitation in that it requires the input stream to be finite. However, it allows for parallel execution of the pipeline.

The above is the detailed content of How Can I Efficiently Generate Consecutive Pairs from a Java Stream?. 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