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
Release: 2024-11-29 08:19:10
Original
191 people have browsed it

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

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!

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