Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java8 equivalent for ruby's each_with_index

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.

like image 242
Muhammad Hewedy Avatar asked Apr 28 '14 17:04

Muhammad Hewedy


2 Answers

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));
like image 50
nosid Avatar answered Nov 02 '22 06:11

nosid


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);
});
like image 2
emesx Avatar answered Nov 02 '22 04:11

emesx