有時候需要給集合(如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);
}
}
}