将一个List拆分为n份的方法
public static void main(String[] args) { List<Integer> taskList = new ArrayList<>(); for (int i = 1; i <= 52; i++) { taskList.add(i); } int total = taskList.size(); int threadNum = 5; int remaider = total % threadNum; // 计算出余数 int number = total / threadNum; // 计算出商 int offset = 0;// 偏移量 for (int i = 0; i < threadNum; i++) { if (remaider > 0) { List<Integer> subList = taskList.subList(i * number + offset, (i + 1) * number + offset + 1); remaider--; offset++; System.out.println(subList.get(0) + "--" + subList.get(subList.size() - 1)); } else { List<Integer> subList = taskList.subList(i * number + offset, (i + 1) * number + offset); System.out.println(subList.get(0) + "--" + subList.get(subList.size() - 1)); } } }
打印结果:
1--11
12--22
23--32
33--42
43--52
一种错误的写法:
int page = 10; int pageSize = (total + page - 1) / page; for (int i = 1; i <= page; i++) { List<String> subList = list.subList((i - 1) * pageSize, i == page ? total : i * pageSize); }
例如将6个分为5份,算得每一份size为2(其实只是最大的一份为2),这样前3份就将数据分完了,到第4份就会报IndexOutOfBoundsException.