Is there a concise way to iterate over a stream whilst having access to the index in the stream?
String[] names = {\"Sam\",\"Pamela\", \"Dave\", \"Pascal\",
I found the solutions here when the Stream is created of list or array (and you know the size). But what if Stream is with unknown size? In this case try this variant:
public class WithIndex {
private int index;
private T value;
WithIndex(int index, T value) {
this.index = index;
this.value = value;
}
public int index() {
return index;
}
public T value() {
return value;
}
@Override
public String toString() {
return value + "(" + index + ")";
}
public static Function> indexed() {
return new Function>() {
int index = 0;
@Override
public WithIndex apply(T t) {
return new WithIndex<>(index++, t);
}
};
}
}
Usage:
public static void main(String[] args) {
Stream stream = Stream.of("a", "b", "c", "d", "e");
stream.map(WithIndex.indexed()).forEachOrdered(e -> {
System.out.println(e.index() + " -> " + e.value());
});
}