Java8在Stream的forEach操作时获取index

 

import java.util.Objects;
import java.util.function.BiConsumer;

/**
 * 

* 实施此接口可以使对象成为目标 *

* * @Author REID * @Blog https://blog.csdn.net/qq_39035773 * @GitHub https://github.com/BeginnerA * @Data 2021/2/23 * @Version V1.0 **/ public class ForEachUtils { /** * 对每个元素执行给定的操作 * @param elements 元素 * @param action 每个元素要执行的操作 * @param T */ public static void forEach(Iterable elements, BiConsumer action) { forEach(0, elements, action); } /** * 对每个元素执行给定的操作 * @param startIndex 开始下标 * @param elements 元素 * @param action 每个元素要执行的操作 * @param T */ public static void forEach(int startIndex, Iterable elements, BiConsumer 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 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 list = Arrays.asList("x","y", "z");
        ForEachUtils.forEach(1, list, (index, item) -> {
            log.info(index + " - " + item);
            //输出
            //1 - y
            //2 - z
        });
    }
}

 

你可能感兴趣的:(实用小工具,Java,java,stream)