背景:java裏面經常會遇到把一個list分批處理的需求,這個時候把一個list分割成list<List>嵌套是一個好辦法。
解決辦法三種:1.可以自己寫一個普通的foreach循環多少次加到一個list裏面,然後重新new一個list
2.使用guava的工具類
Lists.partition(要分割的list, 每個小list多少條數據)
3.使用apach的工具類commons-collections4
ListUtils.partition(要分割的list, 每個小list多少條數據)
代碼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("================");
}
}
執行結果:
輸出生成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
================
附上:
1.添加jar配置,這個是可以使用的,低版本的或許可以,不保證
<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.使用這個分割會遇到在foreach不能remove的情況,具體看文章:https://blog.csdn.net/Mint6/article/details/102875278