/**
* 將一個list均分成n個list,主要通過偏移量來實現(xiàn)的
*/
public static <T> List<List<T>> averageList(List<T> source, int n) {
List<List<T>> result = new ArrayList<>();
int remaider = source.size() % n; //(先計算出余數(shù))
int number = source.size() / n; //然后是商
int offset = 0;//偏移量
for (int i = 0; i < n; i++) {
List<T> value;
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;
}
測試一下:
public static void main(String[] args) {
List<Integer> list = new ArrayList<>();
list.add(1);
list.add(2);
list.add(3);
list.add(4);
list.add(5);
list.add(6);
list.add(7);
list.add(8);
list.add(9);
List<List<Integer>> lists = averageList(list, 4);
System.out.println(GfJsonUtil.toJSONString(lists));
}
結(jié)果如下:
[[1,2,3],[4,5],[6,7],[8,9]]
Process finished with exit code 0