Java实现List数据分组

代码包含 :
(1)平均分为n组
(2)需要每组分n个元素

package com.example.security.zmain.test;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 数量计算
 */
public class NumberToCalculate {
    public static void main(String[] args) {
        List<Map> studentList = new ArrayList<>();
        for (int q = 0; q < 212; q++) {
            Map map = new HashMap();
            map.put("XH",q);
            map.put("EMAIL",q+"@qq.com");
            studentList.add(map);
        }
        List<List<Map>> a = averageAssign(studentList,5);
        for (int i = 0; i < a.size(); i++) {
            List<Map> b = a.get(i);
            System.out.println("一共五组。当前组数量为:"+b.size()+"个");
        }
        List<List<Map>> c = fixedGrouping(studentList,50);
        System.out.println("每组50个:总共:"+c.size()+"组");

    }

    /**
     * 将一组数据平均分成n组
     *
     * @param source 要分组的数据源
     * @param n      平均分成n组
     * @param <T>
     * @return
     */
    public static <T> List<List<T>> averageAssign(List<T> source, int n) {
        List<List<T>> result = new ArrayList<List<T>>();
        int remainder = source.size() % n;  //(先计算出余数)
        int number = source.size() / n;  //然后是商
        int offset = 0;//偏移量
        for (int i = 0; i < n; i++) {
            List<T> value = null;
            if (remainder > 0) {
                value = source.subList(i * number + offset, (i + 1) * number + offset + 1);
                remainder--;
                offset++;
            } else {
                value = source.subList(i * number + offset, (i + 1) * number + offset);
            }
            result.add(value);
        }
        return result;
    }
    /**
     * 将一组数据固定分组,每组n个元素
     *
     * @param source 要分组的数据源
     * @param n      每组n个元素
     * @param <T>
     * @return
     */
    public static <T> List<List<T>> fixedGrouping(List<T> source, int n) {
        if (null == source || source.size() == 0 || n <= 0)
            return null;
        List<List<T>> result = new ArrayList<List<T>>();
        int remainder = source.size() % n;//余数
        int size = (source.size() / n);//商 不算余数 要分多少组。有余数的话下面有单独处理余数数据的
        for (int i = 0; i < size; i++) {//循环要分多少组
            List<T> subset = null;
            subset = source.subList(i * n, (i + 1) * n);//截取list
            result.add(subset);
        }
        if (remainder > 0) {//有余数的情况下把余数得到的数据再添加到list里面
            List<T> subset = null;
            subset = source.subList(size * n, size * n + remainder);
            result.add(subset);
        }
        return result;
    }
}

  • 2
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值