在工作过程中,我们可能需要将已经查询出来的大集合,改造为大集合中包含小集合,每个小集合的集合长度为固定的。这时就可以用下面的方法来实现:
/**
* 将集合按指定数量分组
*
* @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) {
throw 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, Math.min((count + quantity), list.size()))));
count += quantity;
}
return wrapList;
}