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

How to Efficiently Iterate Java 8 Streams with Indices?

Susan Sarandon
Susan SarandonOriginal
2024-12-17 07:26:24397browse

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());

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());

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!

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