【java】LIst切割----划分 List为几个LIst的几种工具类 1.按照目标份数划分 2.按照目标容量划分 【适用场景:mybatis分批次In查询,放置In拼接sql过长】

如题,示例代码如下:

/**
     * 1> 按照份数---划分list
     * @param source
     * @param num    想要划分成多少份
     * @return
     */
    public static <T> List<List<T>> splitListForNum(List<T> source,int num){
        List<List<T>> result=new ArrayList<List<T>>();
        int remaider=source.size()%num;  //(先计算出余数)
        int number=source.size()/num;  //然后是商
        int offset=0;//偏移量
        for(int i=0;i<num;i++){
            List<T> value=null;
            if(remaider>0){
                value=source.subList(i*number+offset, (i+1)*number+offset+1);
                remaider--;
                offset++;
            }else{
                value=source.subList(i*number+offset, (i+1)*number+offset);
            }
            result.add(value);
        }
        return result;
    }

    /**
     * 2> 根据目标容量 划分List
     * @param source
     * @param capacity 划分完成的单个List容量
     * @param <T>
     * @return
     */
    public static <T> List<List<T>> splitListBycapacity(List<T> source,int capacity){
        List<List<T>> result=new ArrayList<List<T>>();
        if (source != null){
            int size = source.size();
            if (size > 0 ){
                for (int i = 0; i < size;) {
                    List<T> value = null;
                    int end = i+capacity;
                    if (end > size){
                        end = size;
                    }
                    value = source.subList(i,end);
                    i = end;

                    result.add(value);
                }

            }else {
                result = null;
            }
        }else {
            result = null;
        }


        return result;
    }



    public static void main(String[] args) {
        List<Integer> all = new ArrayList<>();
        int a= 1000;
        for (int i = 0; i < a; i++) {
            all.add(i+1);
        }

        List<List<Integer>> split = splitListBycapacity(all,333);
        System.out.println(split.size());
        for (List<Integer> strings : split) {
            System.out.println(strings.size());
        }

    }

 【待优化】==============================================

posted @ 2018-07-27 12:35  Angel挤一挤  阅读(2905)  评论(0编辑  收藏  举报