分割List集合
程序员文章站
2022-07-13 17:35:00
...
工作中需要批量插入数据库,但是可能数据量太大,一次性插入会出现问题,故将原有的List集合按照一定的尺寸进行分割,然后将分割后的单个小集合做批量插入。分割的实现如下:
/**
*
* @description 分割集合
* @param
* oldList:要分割的目标集合
* batchSize:用户传入的每个批次的元素个数
* @return List<List> 分割后的集合集
* @date 2017年7月13日
*/
public static <T> List<List<T>> splitList(List<T> oldList, int batchSize) {
if (batchSize < 1)
return null;
List<List<T>> result = new ArrayList<List<T>>();
int size = oldList.size();
int count = (size + batchSize - 1) / batchSize;
for (int i = 0; i < count; i++) {
int fromIndex = i * batchSize;
int toIndex = (i + 1) * batchSize > size ? size : (i + 1) * batchSize;
List<T> subList = oldList.subList(fromIndex, toIndex);
result.add(subList);
}
return result;
}
测试代码如下:
import junit.framework.Assert;
import org.junit.Before;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
/**
* Created by dell on 2017-07-13.
*/
public class ListUtilTest {
List list;
/*
得到一个伪随机字符串
*/
public static String getRandomString(int length) {
String base = "abcdefghijklmnopqrstuvwxyz0123456789";
Random random = new Random();
StringBuffer sbr = new StringBuffer();
for (int i = 0; i < length; i++) {
int number = random.nextInt(base.length());
sbr.append(base.charAt(number));
}
return sbr.toString();
}
@Before
public void initList() {
list = new ArrayList<>();
UserInfo ui;
for(int i = 1; i < 29; i++) {
ui = new UserInfo();
ui.setLoginName(i + getRandomString(5));
ui.setPassword(getRandomString(8));
list.add(ui);
}
}
@Test
public void testSplitList() {
List<List> lists = ListUtil.splitList(list, 10);
Assert.assertEquals(3, lists.size());
Assert.assertTrue(lists.get(0).size() == lists.get(1).size());
Assert.assertEquals(8, lists.get(2).size());
Assert.assertEquals(28, lists.get(0).size() + lists.get(1).size() + lists.get(2).size());
}
}