list集合均分n个集合的两种方法
2019-02-20 本文已影响0人
練碩
/**
* 将一个list均分成n个list,主要通过偏移量来实现的
*
* @param
* @return
*/
public static List>createList(List targe, int size) {
List> listArr =new ArrayList>();
//获取被拆分的数组个数
int arrSize = targe.size() % size ==0 ? targe.size() / size : targe.size() / size +1;
for (int i =0; i < arrSize; i++) {
List sub =new ArrayList();
//把指定索引数据放入到list中
for (int j = i * size; j <= size * (i +1) -1; j++) {
if (j <= targe.size() -1) {
sub.add(targe.get(j));
}
}
listArr.add(sub);
}
return listArr;
}
public static List>averageAssign(List source, int n) {
List> result =new ArrayList>();
int remaider = source.size() % n; //(先计算出余数)
int number = source.size() / n; //然后是商
int offset =0;//偏移量
for (int i =0; i < n; i++) {
List value =null;
if (remaider >0) {
value = source.subList(i * number + offset, (i +1) * number + offset +1);
remaider--;
offset++;
}else {
value = source.subList(i * number + offset, (i +1) * number + offset);
}
result.add(value);
}
return result;
}