java8在Stream的forEach操作时获取index

时间:2019-07-15 17:22:51   收藏:0   阅读:1923
import java.util.Objects;
import java.util.function.BiConsumer;

/**
 * 
 * @author yangzhilong
 * @date 7/15/2019
 */
public class ForEachUtils {
    
    public static <T> void forEach(int startIndex,Iterable<? extends T> elements, BiConsumer<Integer, ? super T> action) {
        Objects.requireNonNull(elements);
        Objects.requireNonNull(action);
        for (T element : elements) {
            action.accept(startIndex++, element);
        }
    }
}

使用:

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

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

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!