for each
loops are a nice syntactic abbreviation to iterate over all elements in a List
:
for (Object object : list) {
// do something with the object
}
However, when I also need the index of the element being processed in each iteration, I have to 'fall back' to the old style:
for (int i = 0; i < list.size(); i++) {
Object object = list.get(i);
// do something with the object and its index
}
Also, if the list is not a random-access one (for example a LinkedList
), to avoid quadratic complexity of iteration I would have to write something like:
int i = 0;
for (Object object : list) {
// do something with the object and its index
i++;
}
Is there any more convenient form to get the element and its index in each iteration (maybe Java 8 streams API combined with some short lambdas)?
The best approach I've been able to come up to so far is to create my custom reusable functional interface:
@FunctionalInterface
public interface WithIndex<T> {
void accept(int i, T t);
public static <T> void forEach(Collection<T> collection, WithIndex<T> consumer) {
int i = 0;
for (T t : collection) {
consumer.accept(i++, t);
}
}
}
Then I can iterate the collection the following way:
public class Main {
public static void main(String[] args) {
List<String> list = Arrays.asList("a", "b", "c");
WithIndex.forEach(list, (i, word) -> {
System.out.println("index=" + i + ", element=" + word);
});
}
}