zoukankan      html  css  js  c++  java
  • java8在Stream的forEach操作时获取index

     
    import java.util.Objects;
    import java.util.function.BiConsumer;
    
    /**
     * 
     * @author yangzhilong
     * @date 7/15/2019
     */
    public class ForEachUtils {
        
        /**
         * 
         * @param <T>
         * @param startIndex 开始遍历的索引
         * @param elements 集合
         * @param action 
         */
        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);
            }
        }
    }

    使用:

    ForEachUtils.forEach(0, list, (index, item) -> {
                
    });

    说明:第一个参数为起始索引,第二个是要遍历的集合,第三个参数为BiConsumer类型的处理器。

    单元测试:

    import java.util.Arrays;
    import java.util.List;
    
    import org.junit.Test;
    
    import lombok.extern.slf4j.Slf4j;
    
    /**
     * @author yangzhilong
     * @date 7/15/2019
     */
    @Slf4j
    public class ForEachUtilsTest {
        @Test
        public void test() {
            List<String> list = Arrays.asList("1","2", "3");
            ForEachUtils.forEach(0, list, (index, item) -> {
                log.info(index + " - " + item);
            });
        }
        @Test
        public void test1() {
            List<String> list = Arrays.asList("x","y", "z");
            ForEachUtils.forEach(1, list, (index, item) -> {
                log.info(index + " - " + item);
            });
        }
    }

    输出:

    0 - 1
    1 - 2
    2 - 3
    1 - y
    2 - z
  • 相关阅读:
    使用VSCode创建简单的Razor Webapp--1.入门
    ASP.NET Razor 常用示例
    ASP.NET Razor 语法
    ASP.NET Razor简介
    EF CodeFirst 一对一、一对多、多对多关系
    mysql外键
    EF CodeFirst 之 Fluent API
    替换JDK 对eclipse的影响?
    mysql数据库,安装 !创建!...详解!
    Apache的commons工具类
  • 原文地址:https://www.cnblogs.com/yangzhilong/p/11189982.html
Copyright © 2011-2022 走看看