封装一个方法按照指定大小拆分一个集合

1.场景、意义:

(1)在有的业务场景下,集合大小受限制不能超过固定长度,可以拆分

(2)提高系统性能,将大量数据拆分成小批次可以减轻单次处理的压力,提高系统的吞吐量和响应速度。

2.方法签名:

/**
 * 将集合按照指定的批次大小进行拆分。
 *
 * @param batchSize 批次大小
 * @param collection 需要拆分的集合
 * @return 拆分后的集合列表
 */
public static <T> List<List<T>> splitIntoBatches(int batchSize, List<T> collection) {
    List<List<T>> batches = new ArrayList<>();
    for (int i = 0; i < collection.size(); i += batchSize) {
        // 从i开始取batchSize个元素,如果剩余元素不足batchSize,则取到集合末尾
        batches.add(new ArrayList<>(collection.subList(i, Math.min(collection.size(), i + batchSize))));
    }
    return batches;
}

主方法:

public static void main(String[] args) {
        List<List<Integer>> lists = splitIntoBatches(3, Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10));
        System.out.println(lists);
    }

打印出来的结果:

[[1, 2, 3], [4, 5, 6], [7, 8, 9], [10]]

3.优化:用Stream API 来简化代码

public static <T> List<List<T>> splitIntoBatches(int batchSize, List<T> collection) {
    List<List<T>> batches = new ArrayList<>();
    IntStream.range(0, (int) Math.ceil((double) collection.size() / batchSize))
            .forEach(n -> batches.add(
                    collection.stream()
                            .skip(n * batchSize)
                            .limit(batchSize)
                            .collect(Collectors.toList())
            ));
    return batches;
}

4.使用第三方库也可以,例如 Apache Commons Collections 中的 Iterables.partition 方法。

依赖:

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-collections4</artifactId>
    <version>4.4</version>
</dependency>

方法签名:

import org.apache.commons.collections4.IterablePartition;
import org.apache.commons.collections4.iterators.IterablePartitionIterator;

import java.util.*;

public class BatchSplitter {

    public static <T> List<List<T>> splitIntoBatches(int batchSize, List<T> collection) {
        Iterable<List<T>> iterable = Iterables.partition(collection, batchSize);
        List<List<T>> batches = new ArrayList<>();
        for (List<T> batch : iterable) {
            batches.add(batch);
        }
        return batches;
    }

    public static void main(String[] args) {
        List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9);
        List<List<Integer>> batches = splitIntoBatches(3, numbers);
        System.out.println(batches); // 输出 [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
    }
}

5.拓展: 我的应用场景还需要把集合中的元素用逗号拼接成一个字符串。

可以用这个方法

String userIds = String.join(",", subList);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值