将List分成N份用于多线程处理,提高数据处理效率。
public static <T> List<List<T>> averageAssign(List<T> source, int n) {
List<List<T>> result = new ArrayList<List<T>>();
int remaider = source.size() % n; //(先计算出余数)
int number = source.size() / n; //然后是商
int offset = 0;//偏移量
for (int i = 0; i < n; i++) {
List<T> 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;
}
//每个片段长度相差最大为1
public static <T> List<List<T>> averageAssign2(List<T> source, int n) {
List<List<T>> result = new ArrayList<List<T>>();
int remainder = source.size() % n; //(先计算出余数)
int number = source.size() / n; //然后是商
//记录以保存的总数
int size = 0;
for (int i = 0; i < n; i++) {
List<T> value = null;
if(i<remainder){
value = source.subList(size, size + number + 1);
}else {
value = source.subList(size,size + number);
}
size += value.size();
result.add(value);
}
return result;
}
//相对均匀
public static <T> List<List<T>> averageAssign(List<T> source, int n) {
List<List<T>> result = new ArrayList<List<T>>();
int remaider = source.size() % n; //(先计算出余数)
int number = source.size() / n; //然后是商
//如果没有余数则均分
if (remaider != 0) {
number++;
}
int remainder = source.size() % number;
for (int i = 0; i < n; i++) {
List<T> ts = null;
if (i < n - 1 || remaider == 0) {
ts = source.subList(i * number, (i + 1) * number);
} else {//当有余数时,最后一组去余数长度
ts = source.subList(source.size() - remainder, source.size());
}
result.add(ts);
}
return result;
}