一、代碼
public class BatchProcess {
public static void main(String[] args) {
List<Integer> totalList = new ArrayList<>();
for (int i = 1; i <= 100; i++) {
totalList.add(i);
}
batchProcessList(totalList);
}
// 將 totalList 集合分成多批進行處理(每一批 batchList)
public static void batchProcessList(List<Integer> totalList) {
Integer BATCH_COUNT = 20;
List<Integer> batchList = new ArrayList<>();
if (!CollectionUtils.isEmpty(totalList)) {
for (int i = 0; i < totalList.size(); i++) {
batchList.add(totalList.get(i));
// 如果分批的集合填充滿了元素或者填充的是最后一個元素
if ((Objects.nonNull(batchList) && Objects.equals(batchList.size(), BATCH_COUNT)) || Objects.equals((totalList.size() - 1), i)) {
System.out.println(batchList);
System.out.println("------------------------------------------");
// 執行完了處理邏輯之后,將 batchList 的元素清空
batchList.clear();
}
}
}
}
}
二、測試結果