List集合指定每个集合的数量拆分成一个大的集合 返回List<List<T>>

package com.tuan.common.utils;

import java.util.AbstractList;
import java.util.ArrayList;
import java.util.List;

/**
 * List拆分多个list
 * @author DuanLinpeng
 * @date 2021/01/08 19:15
 **/
public class ListSplitUtils {

    public static <T> List<List<T>> partition(final List<T> list, final int size) {
        if (list == null) {
            throw new NullPointerException("List must not be null");
        }
        if (size <= 0) {
            throw new IllegalArgumentException("Size must be greater than 0");
        }
        return new Partition<>(list, size);
    }

    private static class Partition<T> extends AbstractList<List<T>> {
        private final List<T> list;
        private final int size;

        private Partition(final List<T> list, final int size) {
            this.list = list;
            this.size = size;
        }

        @Override
        public List<T> get(final int index) {
            final int listSize = size();
            if (index < 0) {
                throw new IndexOutOfBoundsException("Index " + index + " must not be negative");
            }
            if (index >= listSize) {
                throw new IndexOutOfBoundsException("Index " + index + " must be less than size " +
                        listSize);
            }
            final int start = index * size;
            final int end = Math.min(start + size, list.size());
            return list.subList(start, end);
        }

        @Override
        public int size() {
            return (int) Math.ceil((double) list.size() / (double) size);
        }

        @Override
        public boolean isEmpty() {
            return list.isEmpty();
        }
    }

    public static void main(String[] args) {
        List<String> list = new ArrayList<String>();
        for (int i=0; i<1000;i++){
            list.add(i+"");
        }
        List<List<String>> partition = ListSplitUtils.partition(list, 100);
        for (int i=0; i<partition.size();i++){
            System.out.println("i=" +(i+1)+"组 >>>"+ partition.get(i).size());
        }
    }

}

测试结果:

i=1>>>100
i=2>>>100
i=3>>>100
i=4>>>100
i=5>>>100
i=6>>>100
i=7>>>100
i=8>>>100
i=9>>>100
i=10>>>100
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值