I wonder, if there's some stream operation that can do as each_with_index
in ruby.
Where each_with_index
iterates over the value as well as the index of the value.
There is no stream operation specifically for that purpose. But you can mimic the functionality in several ways.
Index variable: The following approach works fine for sequential streams.
int[] index = { 0 };
stream.forEach(item -> System.out.printf("%s %d\n", item, index[0]++));
External iteration: The following approach works fine for parallel streams, as long as the original collection supports random access.
List<String> tokens = ...;
IntStream.range(0, tokens.size()).forEach(
index -> System.out.printf("%s %d\n", tokens.get(index), index));
You can reduce
it
<T> void forEachIndexed(Stream<T> stream, BiConsumer<Integer, T> consumer) {
stream.reduce(0, (index, t) -> {
consumer.accept(index, t);
return index + 1;
}, Integer::max);
}
this way:
List<Integer> ints = Arrays.asList(1, 2, 4, 6, 8, 16, 32);
forEachIndexed(ints.stream(), (idx, el) -> {
System.out.println(idx + ": " + el);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With