项目遇到这种场景,一个很大List集合对象,需要批量的插入到数据库中,为了提高保存的效率,采用切割的方法,将一个大的集合,切割成多个固定大小的多个集合,再分多次,批量将这些集合保存入库,前提交代清楚,程序员还是看代码比较直接,代码如下:
封装的核心Util类
public class ChoppedUtil {
//第一个参数表示要切割的List集合,第二个参数表示分割后的集合大小
public static <T> List<List<T>> chopped(List<T> list, final int L) {
List<List<T>> parts = new ArrayList<List<T>>();
final int N = list.size();
for (int i = 0; i < N; i += L) {
parts.add(new ArrayList<T>(
list.subList(i, Math.min(N, i + L)))
);
}
return parts;
}
}
使用方式:
List<Student> list = new ArrarList<>();
list.add(new Student());
list.add(new Student());
list.add(new Student());
...........
List<List<Student>> choppedList = ChoppedUtil.chopped(list ,100);
for (List<Student> subList : choppedList) {
studentDao.save(subList);
}