← 中文资源

简体中文版本

用 subList 把列表切成批次

用 subList 视窗把列表切成定长批次,让批量调用尊重接口限额;批次是原列表的视图,遍历期间保持只读,尾批自动收窄,不再复制数据。

阅读英文原文

实现说明

用 subList 把列表切成批次以类 BatchSender和函数 chunk、main为骨架。 这个文件只在 for (int i = 0; i < source.size(); i += size) 里循环。代码不会带着坏状态静默继续,守卫一命中就抛 IllegalArgumentException。

使用要点

  • 跑完文件,输出里会留下标记——send batch:、one batch:。
  • main 的演示流程是 chunk——跑一遍文件,这条流程从头到尾可见。

常见问题

前置条件不成立会发生什么?

代码会拒绝继续:抛出 IllegalArgumentException,此时状态仍可恢复。

运行「用 subList 把列表切成批次」会打印什么?

不用做任何设置,直接把文件跑完——输出里的 send batch:、one batch: 标签标明各步骤。

主要签名是 static <T> List<List<T>> chunk(List<T> source, int size)

核心语句

throw new IllegalArgumentException("size must be positive: " + size);
for (int i = 0; i < source.size(); i += size) {
    batches.add(source.subList(i, Math.min(i + size, source.size())));
}

代码示例

import java.util.ArrayList;
import java.util.List;

public class BatchSender {

    // batches are views over the original list: the list stays unmodified during iteration and batch contents remain read-only
    static <T> List<List<T>> chunk(List<T> source, int size) {
        if (size <= 0) {
            throw new IllegalArgumentException("size must be positive: " + size);
        }
        List<List<T>> batches = new ArrayList<>();
        for (int i = 0; i < source.size(); i += size) {
            batches.add(source.subList(i, Math.min(i + size, source.size())));
        }
        return batches;
    }

    public static void main(String[] args) {
        List<Integer> ids = List.of(11, 22, 33, 44, 55, 66, 67);

        // fixed-size slices: the tail batch shrinks automatically when fewer than size remain
        for (List<Integer> batch : chunk(ids, 3)) {
            System.out.println("send batch: " + batch);
        }

        // when size exceeds the total there is exactly one batch
        System.out.println("one batch: " + chunk(ids, 100));
    }
}