The List collection is cut into multiple sets of fixed length

When the project encounters this kind of scenario, a large List collection object needs to be inserted into the database in batches. In order to improve the efficiency of storage, a cutting method is adopted to cut a large collection into multiple fixed-size multiple collections. Divide it several times, save these collections in batches, and submit them to the library. The programmer still looks at the code directly. The code is as follows:
the core Util class of the package

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

How to use:

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

Guess you like

Origin blog.csdn.net/wujian_csdn_csdn/article/details/105657073