批量执行任务时,总是需要关注许多的边界问题
Example比如需要打印1-100的数字,每一批10个
ListworkList = new ArrayList<>(); for (int i = 0; i < 100; i++) { workList.add(i + 1); } BatchUtil.process(10, workList, (list) -> { System.out.println(list); });
使用lamada简写
BatchUtil.process(10, workList, System.out::println);代码实现
package com.seewoedu.train.utils;
import java.util.List;
public class BatchUtil {
public static void process(int batchSize,
List workList,
BatchFunction function) {
if (batchSize <= 0) {
return;
}
int index = 0;
int totalSize = workList.size();
while (index < totalSize) {
if (index + batchSize > totalSize) {
function.execute(workList.subList(index, totalSize));
} else {
function.execute(workList.subList(index, index + batchSize));
}
index += batchSize;
}
}
@FunctionalInterface
public interface BatchFunction {
void execute(List list);
}
}



