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