I was not able to find a forEach method which calls a lamda with the current object and the current index.
Unfortunately this is not implemented in java8, so following implementation is not possible:
List<String> list = Arrays.asList("one", "two");
list.forEach((element, index) -> System.out.println(String.format("[%d] : %s", index, element)));
I know a simple way to do this is to use the for each loop with a index integer:
List<String> list = Arrays.asList("one", "two");
int index = 0;
for (String element : list) {
System.out.println(String.format("[%d] : %s", index++, element));
}
I think the common code to init a index intetger and to increment it for each iteration should be moved to a method. So I defined my own forEach
method:
public static <T> void forEach(@NonNull Iterable<T> iterable, @NonNull ObjIntConsumer<T> consumer) {
int i = 0;
for (T t : iterable) {
consumer.accept(t, i++);
}
}
And I can use it like:
List<String> list = Arrays.asList("one", "two");
forEach(list, (element, index) -> System.out.println(String.format("[%d] : %s", index, element)));
I was not able to find a similar implementation in any util library (e.g. guava). So I have following questions:
- Is there a reason why there is no an utility which provides me this functionality?
- Is there a reason why this is not implemented in java
Iterable.forEach
methdod? - Is there a good utility I didn't find which provides this functionality?