Home > Java > javaTutorial > How Can I Iterate Through a Java 8 Stream While Accessing Element Indices?

How Can I Iterate Through a Java 8 Stream While Accessing Element Indices?

Patricia Arquette
Release: 2024-12-27 14:53:10
Original
785 people have browsed it

How Can I Iterate Through a Java 8 Stream While Accessing Element Indices?

Iterating a Stream with Indices in Java 8: A Concise Solution

To effectively iterate over a stream and access indices, several approaches are available.

Using a Stream of Indices

The cleanest solution is to create a stream of indices and filter it based on the stream's elements:

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 approach ensures that the resulting list only contains elements that meet the index-based criterion.

Using an AtomicInteger Counter

Another alternative is to maintain a mutable counter within the stream:

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 provides a familiar syntax similar to for loops. However, it's crucial to note that this approach can potentially break when used on a parallel stream as items may not be processed in order.

Ultimately, the choice of approach depends on the specific requirements and performance considerations of the application.

The above is the detailed content of How Can I Iterate Through a Java 8 Stream While Accessing Element Indices?. For more information, please follow other related articles on the PHP Chinese website!

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