彌補Java的foreach不能獲取index的不足:java
import java.util.Objects;
import java.util.function.BiConsumer;
public class IterableUtils {
public static <T> void forEach(Integer startIndex,
Iterable<? extends T> elements,
BiConsumer<Integer, ? super T> action
) {
Objects.requireNonNull(elements);
Objects.requireNonNull(action);
for (T element : elements) {
action.accept(startIndex++, element);
}
}
}
複製代碼
調用:bash
IterableUtils.forEach(0, list, (index, value) -> {
//TODO
});
複製代碼