Background : Java often encounters the need to process a list in batches. At this time, it is a good way to divide a list into list<List> nesting.
There are three solutions : 1. You can write an ordinary foreach loop and add it to a list how many times, and then renew a list
2. Use Guava's tools
Lists.partition(要分割的list, 每个小list多少条数据)
3. Use apach's tool class commons-collections4
ListUtils.partition(要分割的list, 每个小list多少条数据)
Code demo
package formal.util.list;
import com.google.common.collect.Lists;
import org.apache.commons.collections4.ListUtils;
import java.util.ArrayList;
import java.util.List;
/**
* @author :
* @date : 2019/11/2
* @description:分批处理,分批插入
*/
public class PartialList {
public static void main(String[] args) {
/*1.正常情况,使用guava工具类分类,包:com.google.common.collect.Lists*/
List<Integer> intList1 = Lists.newArrayList(1, 2, 3, 4, 5, 6, 7, 8);
List<List<Integer>> subs1 = Lists.partition(intList1, 3);
PartialList.printList2(subs1);
/*2.list为empty*/
List<Integer> intList2 = new ArrayList<>();
/*3.分组大于数据*/
List<List<Integer>> subs2 = Lists.partition(intList2, 10);
PartialList.printList2(subs2);
System.out.println("以下是apache的工具类=================================");
/*正常情况,使用apache工具类分类,包:com.google.common.collect.Lists*/
List<Integer> intList1apache = Lists.newArrayList(1, 2, 3, 4, 5, 6, 7, 8);
List<List<Integer>> subs1apache = ListUtils.partition(intList1apache, 3);
PartialList.printList2(subs1apache);
/*list为empty*/
List<Integer> intList2apache = new ArrayList<>();
/*2.分组大于数据*/
List<List<Integer>> subs2apache = ListUtils.partition(intList2apache, 10);
PartialList.printList2(subs2apache);
}
public static void printList2(List<List<Integer>> listList) {
System.out.println("输出生成list信息:" + listList.size());
for (List<Integer> sub : listList) {
System.out.println("进来了");
for (Integer integer : sub) {
System.out.println(integer);
}
}
System.out.println("================");
}
}
Execution result :
输出生成list信息:3
进来了
1
2
3
进来了
4
5
6
进来了
7
8
================
输出生成list信息:0
================
以下是apache的工具类=================================
输出生成list信息:3
进来了
1
2
3
进来了
4
5
6
进来了
7
8
================
输出生成list信息:0
================
Attached :
1. Add jar configuration , this can be used, lower version may be possible, not guaranteed
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>27.1-jre</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>4.0</version>
</dependency>
2. Using this segmentation will encounter the situation that the foreach cannot be removed , see the article for details: https://blog.csdn.net/Mint6/article/details/102875278