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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM