Home > Java > javaTutorial > How to Efficiently Iterate Java 8 Streams with Indices?

How to Efficiently Iterate Java 8 Streams with Indices?

Susan Sarandon
Release: 2024-12-17 07:26:24
Original
392 people have browsed it

How to Efficiently Iterate Java 8 Streams with Indices?

Iterating Streams with Indices in Java 8

In Java 8, streams provide a powerful way to process collections of elements. However, iterating over a stream while accessing indices can be challenging.

The provided code snippet demonstrates an elaborate solution using zip and SimpleEntry to pair indices and stream elements. However, is there a more concise approach?

Fortunately, yes. You can start with a stream of indices and filter based on the index by comparing it to the corresponding element's length. Here's an example:

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

Alternative Approach

Alternatively, you can maintain an ad hoc counter using a mutable object like AtomicInteger. However, this method should not be used on parallel streams as it can lead to incorrect results due to out-of-order processing. An example:

AtomicInteger index = new AtomicInteger();
List<String> list = Arrays.stream(names)
                          .filter(n -> n.length() <= index.incrementAndGet())
                          .collect(Collectors.toList());
Copy after login

The above is the detailed content of How to Efficiently Iterate Java 8 Streams with Indices?. 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