Home > Java > javaTutorial > How Can I Efficiently Iterate Through a Java 8 Stream with Index Access?

How Can I Efficiently Iterate Through a Java 8 Stream with Index Access?

Susan Sarandon
Release: 2024-12-18 14:32:17
Original
544 people have browsed it

How Can I Efficiently Iterate Through a Java 8 Stream with Index Access?

Concise Index-Based Stream Iteration in Java 8

Many programming tasks involve iterating over a data structure while accessing the corresponding index. Java 8 streams provide a wide range of operations for stream processing, but there is no explicit way to obtain the index during iteration.

The provided Java code demonstrates a rather verbose approach using IntStream, boxed(), zip(), filter(), map(), and collect(). While it achieves the desired result, its length and complexity mar its elegance.

Cleanest Method:

The most concise approach is to start from a stream of indices:

String[] names = {"Sam", "Pamela", "Dave", "Pascal", "Erik"};
IntStream.range(0, names.length)
         .filter(i -> names[i].length() <= i)
         .mapToObj(i -> names[i])
         .collect(Collectors.toList());
Copy after login

This method constructs a stream of indices from 0 to the length of the array, filters the indices based on the length of the corresponding string, maps the indices to the corresponding strings, and collects the results into a list.

Alternative Method:

Another option is to maintain an ad hoc index counter using a mutable object like an AtomicInteger:

String[] names = {"Sam", "Pamela", "Dave", "Pascal", "Erik"};
AtomicInteger index = new AtomicInteger();
List<String> list = Arrays.stream(names)
                          .filter(n -> n.length() <= index.incrementAndGet())
                          .collect(Collectors.toList());
Copy after login

This method preserves the familiarity of for-loop-based index incrementing. However, it should be noted that using this method on a parallel stream can potentially result in incorrect behavior due to the non-deterministic ordering of parallel processing.

The above is the detailed content of How Can I Efficiently Iterate Through a Java 8 Stream with Index Access?. 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