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