Home >Java >javaTutorial >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());
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());
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!