天天看點

分割List集合

工作中需要批量插入資料庫,但是可能資料量太大,一次性插入會出現問題,故将原有的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;
	}
           
分割List集合

測試代碼如下:

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());
    }
}
           

繼續閱讀