When using the java8 forEach method, you may want an index (serial number). At that time, if you try to use the counter variable, you cannot update it in the lambda, so you have to use an array.
I can't do this
int i = 1;
java.util.stream.Stream.of("a", "b", "c", "d").forEach(s -> {
System.out.println(i + ": " + s);
i++;
});
You can do this
int i[] = { 1 };
java.util.stream.Stream.of("a", "b", "c", "d").forEach(s -> {
System.out.println(i[0] + ": " + s);
i[0]++;
});
Either way, the outlook is not good, so I want to make it look like this.
I want to do this
java.util.stream.Stream.of("a", "b", "c", "d").forEach(withIndex((s, i) -> System.out.println(i + ": " + s)));
So, let's create a utility method.
Class name and method name are appropriate
import java.util.function.Consumer;
import java.util.function.ObjIntConsumer;
public class With {
public static <T> Consumer<T> B(int start, ObjIntConsumer<T> consumer) {
int counter[] = { start };
return obj -> consumer.accept(obj, counter[0]++);
}
}
The initial value can also be set.
did it
java.util.stream.Stream.of("a", "b", "c", "d").forEach(With.B(1, (s, i) -> System.out.println(i + ": " + s)));
Execution result
1: a
2: b
3: c
4: d
[Caution] When executing in parallel in stream, please devise such as using forEachOrdered.
that's all
Recommended Posts