List拆分多个子list的方法

Posted on 2020-02-29 10:42  wzhw2015  阅读(939)  评论(0编辑  收藏  举报

public static <T> List<List<T>> split(List<T> sourceList, int count) {
List<List<T>> resultList = new ArrayList<>();
int size = sourceList.size();
if (size <= count) {
resultList.add(sourceList);
} else {
int listCount = size / count;
int last = size % count;
for (int i = 0; i < listCount; i++) {
List<T> itemList = new ArrayList<T>();
for (int j = 0; j < count; j++) {
itemList.add(sourceList.get(i * count + j));
}
resultList.add(itemList);
}
if (last > 0) {
List<T> itemList = new ArrayList<T>();
for (int i = 0; i < last; i++) {
itemList.add(sourceList.get(listCount * count + i));
}
resultList.add(itemList);
}
}
return resultList;
}

Copyright © 2024 wzhw2015
Powered by .NET 9.0 on Kubernetes