将一个集合按指定大小分割成多个集合(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

posted @ 2021-12-30 15:02  进击的小蔡鸟  阅读(2207)  评论(0编辑  收藏  举报