有时候需要给集合(如List)按数量分组,比如全集太大时,需要分批处理;或效率有点低,分批并发处理。于是,写了个将List按数量分组的方法。
package controller;
import java.util.ArrayList;
import java.util.List;
public class ListGrouper{
/**
* 将集合按指定数量分组
* @param list 数据集合
* @param quantity 分组数量
* @return 分组结果
*/
public static <T> List<List<T>> groupListByQuantity(List<T> list, int quantity) {
if (list == null || list.size() == 0) {
return null;
}
if (quantity <= 0) {
new IllegalArgumentException("Wrong quantity.");
}
List<List<T>> wrapList = new ArrayList<List<T>>();
int count = 0;
while (count < list.size()) {
wrapList.add(new ArrayList<T>(list.subList(count, (count + quantity) > list.size() ? list.size() : count + quantity)));
count += quantity;
}
return wrapList;
}
public static void main(String[] args) {
List<Integer> list = new ArrayList<Integer>();
for (int i = 1; i <= 1011; i++) {
list.add(i);
}
List<List<Integer>> resultList = ListGrouper.groupListByQuantity(list, 50);
for (List<Integer> l : resultList) {
System.out.println(l);
}
}
}