话不多说,直接上代码,直接用
public static <T> List<List<T>> averageList(List<T> source, int n) {
List<List<T>> ret = new ArrayList<List<T>>();
int number = source.size() / n;
int remainder = source.size() % n; // 取余
int offset = 0;//偏移量
for (int i = 0; i < n; i++) {
System.out.println("i:"+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);
}
ret.add(value);
}
return ret;
}
如果想要再去除这里面存在的多余的空list,就加这行代码:
public static <T> List<List<T>> removeEmptyList(List<T> source, int n){
List<List<T>> lists = averageList(source, n);
return lists.stream().filter(i -> i.size() != 0).collect(Collectors.toList());
}