Java8在Stream的forEach操作时获取index

时间:2025-04-12 07:51:20

 

import ;
import ;

/**
 * <p>
 * 实施此接口可以使对象成为目标
 * </p>
 *
 * @Author REID
 * @Blog /qq_39035773
 * @GitHub /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) {
        (elements);
        (action);
        if(startIndex < 0) {
            startIndex = 0;
        }
        int index = 0;
        for (T element : elements) {
            index++;
            if(index <= startIndex) {
                continue;
            }
            (index-1, element);
        }
    }
}

测试:

import ;
import ;

import ;

import .slf4j.Slf4j;


@Slf4j
public class ForEachUtilsTest {
    @Test
    public void test() {
        List<String> list = ("1","2", "3");
        (list, (index, item) -> {
            (index + " - " + item);
            //输出
            //0 - 1
            //1 - 2
            //2 - 3
        });
    }
    @Test
    public void test1() {
        List<String> list = ("x","y", "z");
        (1, list, (index, item) -> {
            (index + " - " + item);
            //输出
            //1 - y
            //2 - z
        });
    }
}