对于系统间数据的交互,都应该进行数据量的限制,那么就经常需要对项目中的数据集合进行分页处理然后进行接口交互,这里整理一个集合的分页处理代码,方便以后使用也希望能帮到大家
/**
* 把集合数据按指定的单页条数拆分
* */
public static <T> List<List<T>> rationing(List<T> source, int n) {
List<List<T>> result = new ArrayList<List<T>>();
//设置初始下标为0,每次成长分页大小,当endIndex等于集合长度时因为有i < list.size()所以也不会出现溢出页
for (int i = 0; i < source.size(); i += n) {
//如果分页toIndex下标大于当前集合长度,那么以集合长度为分页toIndex下标
int endIndex = i + n;
if (endIndex > source.size()) {
endIndex = source.size();
}
//获取到分页后的一页集合
List<T> newList = source.subList(i,endIndex );
result.add(newList);
}
return result;
}
/**
* 把集合数据按指定的总页数均分
* */
public static <T> List<List<T>> averageAssign(List<T> source, int n) {
List<List<T>> result = new ArrayList<List<T>>();
//(先计算出余数)
int remainder = source.size() % n;
//然后是商
int number = source.size() / n;
//偏移量
int offset = 0;
for (int i = 0; i < n; i++) {
List<T> value = null;
if (remainder > 0) {
value = source.subList(i * number + offset, (i + 1) * number + offset + 1);
remainder--;
offset++;
} else {
value = source.subList(i * number + offset, (i + 1) * number + offset);
}
result.add(value);
}
return result;
}