List分组相关操作JAVA实现

package com.example.demo.commontest;

import org.apache.commons.collections4.CollectionUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @describtion list 分割工具类
 * @create-time 10:57 2019/12/10
 **/
public class SubListTest {
    public static void main(String[] args) {
        List<Integer> list = new ArrayList<>();
        for (int i = 0; i < 12; i++) {
            list.add(i);
        }
//        List<List<Integer>> all = groupList(list, 2);
        List<List<Integer>> all = groupList1(list, 10);
        System.out.println(all.size());
        System.out.println(all);

    }

    /*
     * @Description: 按n分割list,并且返回结果
     * 如:12个,10个一组:[[0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [10, 11]]
     * @param: [source 源list, n 每组list的元素个数]
     * @return: java.util.List<java.util.List<T>>
     * @Date: 2019/12/10
     */
    public static <T> List<List<T>> groupList(List<T> source, int n) {
        if(source == null || source.isEmpty() || n <= 0) {
            return Collections.EMPTY_LIST;
        }
        List<List<T>> all = new ArrayList<>();
        int size = source.size();
        int num = size / n + 1;
        for (int i = 0; i < num; i++) {
            List<T> temp;
            if (i * n + size % n == size) {// 判断是最后一个组时的条件
                temp = source.subList(i * n, size);
            } else {
                temp = source.subList(i * n, (i + 1) * n);
            }
            if(!temp.isEmpty()) {
                all.add(temp);
            }
        }
        return all;
    }

    /**
     * @Description: 将一组数据平均分成n组
     * 如:12个,分2组 :[0, 1, 2, 3, 4, 5], [6, 7, 8, 9, 10, 11]
     * @param: [source 源list, n 每组list的元素个数]
     * @return: java.util.List<java.util.List<T>>
     * @Date: 2019/12/10
     */
    public static <T> List<List<T>> groupList1(List<T> source, int n) {
        if(source == null || source.isEmpty() || n <= 0) {
            return Collections.EMPTY_LIST;
        }
        List<List<T>> all = new ArrayList<>();
        int mod = source.size() / n;
        int remainder = source.size() % n;
        int offset = 0;
        for (int i = 0; i < n; i++) {
            List<T> value = null;
            if (remainder > 0) {
                value = source.subList(i * mod + offset, (i + 1) * mod + offset + 1);
                remainder--;
                offset++;
            } else {
                value = source.subList(i * mod + offset, (i + 1) * mod + offset);
            }
            all.add(value);
        }
        return all;
    }

   
}

 

posted @   初见洞洞拐  阅读(188)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
点击右上角即可分享
微信分享提示