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);