Java8在Stream的forEach操作时获取index

这篇博客介绍了一个名为ForEachUtils的Java工具类,它提供了对集合元素进行遍历操作的方法。通过重载forEach方法,允许指定起始下标并使用BiConsumer执行自定义操作。在测试案例中,展示了如何输出元素及其索引,对于理解和自定义集合操作非常有帮助。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

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
        });
    }
}

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值