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

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

DDD
Release: 2024-12-28 19:27:14
Original
742 people have browsed it

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

Concise Stream Iteration with Indices in Java 8

Iterating over a stream in Java 8 while also having access to its indices can be achieved using a variety of methods, with the simplest being to start from a stream of indices.

For instance, the code below generates a stream of integers from 0 to the length of the "names" array, filters out indices where the corresponding string length is greater than the index, and collects the resulting strings into a list:

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

This results in a list containing only "Erik", since its length (4) is less than or equal to its index (4).

An alternative approach, although less concise, is to maintain an ad hoc counter within the filter method. However, it's crucial to note that using this method on a parallel stream might cause the items to be processed out of order.

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

The above is the detailed content of How Can I Efficiently Iterate Through a Java 8 Stream with Access to 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template