集合工具類 (大集合拆分爲多個小集合)

package com.fh.util;

import java.util.ArrayList;
import java.util.List;

/**
 * list 集合工具類
 * @author yuer629
 *
 */
public class ListUtils {
	
	/**
	 * 拆分集合爲多個子集合
	 * @param <T>
	 * @param sourceList 源集合list
	 * @param batchCount 每個子list的最大容量
	 * @return
	 */
	public static<T> List<List<T>> batchList(List<T> sourceList, int batchCount) {
        List<List<T>> returnList = new ArrayList<>();
        int startIndex = 0; // 從第0個下標開始
        while (startIndex < sourceList.size()) {
            int endIndex = 0;
            if (sourceList.size() - batchCount < startIndex) {
                endIndex = sourceList.size();
            } else {
                endIndex = startIndex + batchCount;
            }
            returnList.add(sourceList.subList(startIndex, endIndex));
            startIndex = startIndex + batchCount; // 下一批
        }
        return returnList;
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章