美文网首页
将list均分为n个list

将list均分为n个list

作者: 陈煦缘 | 来源:发表于2018-06-22 17:03 被阅读0次
 /**
     * 将一个list均分成n个list,主要通过偏移量来实现的
     */
    public static <T> List<List<T>> averageList(List<T> source, int n) {
        List<List<T>> result = new ArrayList<>();
        int remaider = source.size() % n;  //(先计算出余数)
        int number = source.size() / n;  //然后是商
        int offset = 0;//偏移量
        for (int i = 0; i < n; i++) {
            List<T> value;
            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;
    }

测试一下:


 public static void main(String[] args) {
        List<Integer> list = new ArrayList<>();
        list.add(1);
        list.add(2);
        list.add(3);
        list.add(4);
        list.add(5);
        list.add(6);
        list.add(7);
        list.add(8);
        list.add(9);
  
        List<List<Integer>> lists = averageList(list, 4);
        System.out.println(GfJsonUtil.toJSONString(lists));
    }

结果如下:


[[1,2,3],[4,5],[6,7],[8,9]]

Process finished with exit code 0

相关文章

网友评论

      本文标题:将list均分为n个list

      本文链接:https://www.haomeiwen.com/subject/amzkyftx.html