Home >Java >javaTutorial >How Can I Iterate Through a Java 8 Stream While Accessing Element Indices?
To effectively iterate over a stream and access indices, several approaches are available.
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());
This approach ensures that the resulting list only contains elements that meet the index-based criterion.
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());
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!