首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >Java 集合List如何按照指定数量大小分割成多个List集合?

Java 集合List如何按照指定数量大小分割成多个List集合?

作者头像
跟着飞哥学编程
发布2022-11-30 21:31:49
发布2022-11-30 21:31:49
1.5K0
举报

直接上工具类代码

代码语言:javascript
复制
package com.xxx.util;

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

public class ListUtils {
	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 <= 1000000; i++) {
			list.add(i+"");
		}
        //将list集合按照2000条数据分割为一个单独的List集合
		List<List<String>> partition = ListUtils.partition(list, 2000);
		System.out.println(partition.size());
	}
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2022-03-21,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档