在日常工作中,经常会遇到需要将list集合进行拆分然后进行操作,比如像在tidb中一个事务默认最多5000条sql statement,或者mysql批量处理时候max_allowed_packet默认大小的限制,一般都需要去把对应数据的集合去拆分然后进行操作。
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.guavagroupId>
<artifactId>guavaartifactId>
<version>20.0version>
dependency>
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.commonsgroupId>
<artifactId>commons-collections4artifactId>
<version>4.1version>
dependency>
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.hutoolgroupId>
<artifactId>hutool-allartifactId>
<version>5.8.3version>
dependency>
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 [email protected]
* @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));
}
}