代码包含 :
(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;
}
}