集合分批保存工具类

2023-12-04  本文已影响0人  天明少侠

集合分批保存工具类

package cn.yto.learn.report;

/**
 * <p>
 * </p>
 */

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;

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

public class BatchSaveUtils {

    /**
     * 将集合分批保存
     *
     * @param originalList 原始集合
     * @param batchSize    每批次的大小
     * @param <T>          集合元素类型
     * @return 保存结果的列表
     */
    public static <T> List<List<T>> batchSave(List<T> originalList, int batchSize) {
        if (originalList == null || originalList.isEmpty() || batchSize <= 0) {
            throw new IllegalArgumentException("Invalid input parameters");
        }

        int totalElements = originalList.size();
        int totalBatches = (int) Math.ceil((double) totalElements / batchSize);

        List<List<T>> result = new ArrayList<>();

        for (int i = 0; i < totalBatches; i++) {
            int startIndex = i * batchSize;
            int endIndex = Math.min(startIndex + batchSize, totalElements);
            List<T> batch = new ArrayList<>(originalList.subList(startIndex, endIndex));
            result.add(batch);
        }

        return result;
    }

    public static void main(String[] args) {
        // 示例用法
        List<Integer> originalList = Lists.newArrayList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10,11,12);
        System.out.println(originalList.size());

        int batchSize = 5;

        List<List<Integer>> batches = batchSave(originalList, batchSize);

        for (int i = 0; i < batches.size(); i++) {
            System.out.println("Batch " + (i + 1) + ": " + batches.get(i).size());
        }

        for (int i = 0; i < batches.size(); i++) {
            System.out.println("Batch " + (i + 1) + ": " + JSON.toJSONString(batches.get(i)));
        }
    }
}

上一篇 下一篇

猜你喜欢

热点阅读