import java.util.Objects;
import java.util.function.BiConsumer;
/**
* <p>
* 实施此接口可以使对象成为目标
* </p>
*
* @Author REID
* @Blog https://blog.youkuaiyun.com/qq_39035773
* @GitHub https://github.com/BeginnerA
* @Data 2021/2/23
* @Version V1.0
**/
public class ForEachUtils {
/**
* 对每个元素执行给定的操作
* @param elements 元素
* @param action 每个元素要执行的操作
* @param <T> T
*/
public static <T> void forEach(Iterable<? extends T> elements, BiConsumer<Integer, ? super T> action) {
forEach(0, elements, action);
}
/**
* 对每个元素执行给定的操作
* @param startIndex 开始下标
* @param elements 元素
* @param action 每个元素要执行的操作
* @param <T> T
*/
public static <T> void forEach(int startIndex, Iterable<? extends T> elements, BiConsumer<Integer, ? super T> action) {
Objects.requireNonNull(elements);
Objects.requireNonNull(action);
if(startIndex < 0) {
startIndex = 0;
}
int index = 0;
for (T element : elements) {
index++;
if(index <= startIndex) {
continue;
}
action.accept(index-1, element);
}
}
}
测试:
import java.util.Arrays;
import java.util.List;
import org.junit.Test;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class ForEachUtilsTest {
@Test
public void test() {
List<String> list = Arrays.asList("1","2", "3");
ForEachUtils.forEach(list, (index, item) -> {
log.info(index + " - " + item);
//输出
//0 - 1
//1 - 2
//2 - 3
});
}
@Test
public void test1() {
List<String> list = Arrays.asList("x","y", "z");
ForEachUtils.forEach(1, list, (index, item) -> {
log.info(index + " - " + item);
//输出
//1 - y
//2 - z
});
}
}