有时候,可能需要按照一定个数,截取大集合。
比如在做批量导入数据时,将一个大集合直接导入,相对来说,将其截成一个个的小集合反而更加效率。那就需要集合截取的方法,如下:
public class ListUtils<T> {
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;
}
}
上边的类使用的方法比较简单,如下:
/**
* 批量导入
* @param tdtgList
*/
@Override
public void addBatch(List<Tdtg> tdtgList) throws Exception {
//即,将其按照每100条截取的方式,再循环批量导入到数据库中
List<List<Tdtg>> resultList = ListUtils.batchList(tdtgList,100);
for(List<Tdtg> xxptFileQzbs:resultList){
tdtgMapper.insertBatch(xxptFileQzbs);
}
}