將一個集合按指定大小分割成多個集合(Stream)


/*
* 由於本人未仔細驗證代碼效果,給大家造成困擾,深感抱歉
* 代碼已更正,如果您在閱讀過程中發現錯誤,請多多提醒,謝謝
* */
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;

/**
 * @ClassName SkipListTest
 * @Description 將一個集合按指定大小分割成多個集合
 * @Author lyn
 * @Date 2021/12/30 14:26
 */
@SuppressWarnings("all")
public class SkipListTest {
    public static void main(String[] args) {
        //1 准備要分割的數據集合(模擬)
        //獲取一個1-10000的集合
        //List<Integer> list = IntStream.range(1, 10000).boxed().collect(Collectors.toList());
        List<Integer> list = Stream.iterate(1, n -> n + 1).limit(10001).collect(Collectors.toList());

        //2 分割的基礎數據
        //子集合的大小
        final int sonSize = 100;
        //分割的份數
        final int copies = (list.size() + sonSize - 1) / sonSize;

        //3 分割方案
        //手動分割
        long startTime = System.currentTimeMillis();
        List<List<Integer>> sonLists = new ArrayList<>();
        Stream.iterate(0, n -> n + 1)
                .limit(copies)
                .parallel()
                .forEach(i -> {
                    int fromIndex = i * sonSize;
                    //int toIndex=fromIndex+sonSize;//原來錯誤版本,並沒有將集合均分,而是一個比一個大
                    //原因:理解錯了stream.skip(n)結合limit(j)方法的使用,skip是要跳過前n個,limit里的參數是要取j個
                    //比如一個集合{1,2,3,4,5,6},要取3-5的數
                    //skip(2).limit(3)
                    int toIndex=sonSize;
                    if (i+1==list.size()){
                        toIndex=list.size()-fromIndex;
                    }

                    sonLists.add(list.stream().skip(fromIndex).limit(toIndex).collect(Collectors.toList()));
                }
        );
        System.err.println("手動分割 總耗時:" + (System.currentTimeMillis() - startTime) + " ms");
        //映射分割(推薦,耗時短,有序)
        startTime = System.currentTimeMillis();
        List<List<Integer>> sonListTwo = IntStream.range(0, copies)
                .boxed()
                .parallel()
                .map(i -> {
                    int fromIndex = i * sonSize;
                    int toIndex=sonSize;
                    if (i+1==list.size()){
                        toIndex=list.size()-fromIndex;
                    }
                    return list.stream().skip(fromIndex).limit(toIndex).collect(Collectors.toList());
                }).collect(Collectors.toList());
        System.err.println("映射分割 總耗時:" + (System.currentTimeMillis() - startTime) + " ms");
    }
}

 img

img


免責聲明!

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



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