好记性不如烂笔头JAVA分批处理数据简单示例
時光功能描述
在处理业务时,经常遇到需要分批次处理数据的场景,例如有105条数据,每次推送20条,分批次推送
最后不足20条数据时,一次性推送全部剩余数据
DEMO示例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
| package shiguang.test;
import java.util.ArrayList; import java.util.List;
public class BatchProcessingExample {
public static void main(String[] args) { List<Integer> responseData = new ArrayList<>(); for (int i = 1; i <= 105; i++) { responseData.add(i); }
int batchSize = 20;
int totalDataSize = responseData.size(); int totalBatches = (int) Math.ceil((double) totalDataSize / batchSize);
for (int batchNumber = 0; batchNumber < totalBatches; batchNumber++) { int startIndex = batchNumber * batchSize; int endIndex = Math.min(startIndex + batchSize, totalDataSize);
List<Integer> batchData = responseData.subList(startIndex, endIndex);
processBatchData(batchData); } }
private static void processBatchData(List<Integer> batchData) { for (Integer data : batchData) { System.out.println("Processing data: " + data); } System.out.println("Batch processing complete."); } }
|