If you want a solution that works with non-RandomAccess
lists as well, you can write yourself a simple utility method:
public static <T> void forEach(List<T> list, BiConsumer<Integer,? super T> c) {
Objects.requireNonNull(c);
if(list.isEmpty()) return;
if(list instanceof RandomAccess)
for(int i=0, num=list.size(); i<num; i++)
c.accept(i, list.get(i));
else
for(ListIterator<T> it=list.listIterator(); it.hasNext(); ) {
c.accept(it.nextIndex(), it.next());
}
}
Then you can use it like: forEach(list, (i,s)->System.out.println(i+"\t"+s));
If you swap the order of element and index, you can use an ObjIntConsumer
instead of BiConsumer<Integer,? super T>
to avoid potential boxing overhead:
public static <T> void forEach(List<T> list, ObjIntConsumer<? super T> c) {
Objects.requireNonNull(c);
if(list.isEmpty()) return;
if(list instanceof RandomAccess)
for(int i=0, num=list.size(); i<num; i++)
c.accept(list.get(i), i);
else
for(ListIterator<T> it=list.listIterator(); it.hasNext(); ) {
c.accept(it.next(), it.previousIndex());
}
}
Then, to be used like forEach(list, (s,i) -> System.out.println(i+"\t"+s));
…