将List集合按长度切分
在日常工作中,经常会遇到需要将list集合进行拆分然后进行操作,比如像在tidb中一个事务默认最多5000条sql statement,或者mysql批量处理时候max_allowed_packet默认大小的限制,一般都需要去把对应数据的集合去拆分然后进行操作。
1. 使用guava
Lists.partition
List<Integer> list = Lists.newArrayList(1,2,3,4,5,6,7,8,9,10);
List<List<Integer>> listList = Lists.partition(list, 4);
listList.forEach(a -> System.out.println(a));
输出结果:
[1, 2, 3, 4]
[5, 6, 7, 8]
[9, 10]
pom文件:
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>20.0</version>
</dependency>
2. 使用commons-collection4
ListUtils.partition
List<Integer> list = Arrays.asList(1,2,3,4,5,6,7,8,9,10);
List<List<Integer>> listList = ListUtils.partition(list, 3);
listList.forEach(a -> System.out.println(a));
输出结果:
[1, 2, 3]
[4, 5, 6]
[7, 8, 9]
[10]
pom文件:
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>4.1</version>
</dependency>
3. 使用hutool
ListUtil.partition
List<Integer> list = Arrays.asList(1,2,3,4,5,6,7,8,9,10);
List<List<Integer>> listList = ListUtil.partition(list, 4);
listList.forEach(a -> System.out.println(a));
输出结果:
[1, 2, 3, 4]
[5, 6, 7, 8]
[9, 10]
pom文件:
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.8.3</version>
</dependency>
- demo
package com.storm.jihe;
import cn.hutool.core.collection.ListUtil;
import com.google.common.collect.Lists;
import org.apache.commons.collections4.ListUtils;
import java.util.Arrays;
import java.util.List;
/**
* @author stormkai@126.com
* @date 2022/10/17 14:30
*/
public class SetSlice {
public static void main(String[] args) {
//guavaPartition();
apachePartition();
//hutoolPartition();
}
private static void hutoolPartition() {
List<Integer> list = Arrays.asList(1,2,3,4,5,6,7,8,9,10);
List<List<Integer>> listList = ListUtil.partition(list, 4);
listList.forEach(a -> System.out.println(a));
}
private static void apachePartition() {
List<Integer> list = Arrays.asList(1,2,3,4,5,6,7,8,9,10);
List<List<Integer>> listList = ListUtils.partition(list, 3);
listList.forEach(a -> System.out.println(a));
}
private static void guavaPartition() {
List<Integer> list = Lists.newArrayList(1,2,3,4,5,6,7,8,9,10);
List<List<Integer>> listList = Lists.partition(list, 4);
listList.forEach(a -> System.out.println(a));
}
}
本文介绍了如何使用Guava、Apache Commons Collections和Hutool库将List拆分成指定长度的子列表,以应对数据库限制。通过实例展示了三种库在列表切分上的应用,并提供了相应的依赖管理。

6104

被折叠的 条评论
为什么被折叠?



