java 对ArrayList进行分页实例代码
java对ArrayList进行分页
概述
系统与系统之间的交互,通常是使用接口的形式。假设B系统提供了一个批量的查询接口,限制每次只能查询50条数据,而我们实际需要查询500条数据,这个时候可以对这500条数据做分批操作,分10次调用B系统的批量接口。
如果B系统的查询接口是使用List作为入参,那么要实现分批调用的话,可以利用ArrayList的subList方法来处理。
代码
sublist方法的定义:
List<E>subList(intfromIndex,inttoIndex);
只需要准确的算出fromIndex和toIndex即可。
数据准备
publicclassTestArrayList{
publicstaticvoidmain(String[]args){
List<Long>datas=Arrays.asList(newLong[]{1L,2L,3L,4L,5L,6L,7L});
}
}
分页算法
importjava.util.Arrays;
importjava.util.List;
publicclassTestArrayList{
privatestaticfinalIntegerPAGE_SIZE=3;
publicstaticvoidmain(String[]args){
List<Long>datas=Arrays.asList(newLong[]{1L,2L,3L,4L,5L,6L,7L,8L});
//总记录数
IntegertotalCount=datas.size();
//分多少次处理
IntegerrequestCount=totalCount/PAGE_SIZE;
for(inti=0;i<=requestCount;i++){
IntegerfromIndex=i*PAGE_SIZE;
//如果总数少于PAGE_SIZE,为了防止数组越界,toIndex直接使用totalCount即可
inttoIndex=Math.min(totalCount,(i+1)*PAGE_SIZE);
List<Long>subList=datas.subList(fromIndex,toIndex);
System.out.println(subList);
//总数不到一页或者刚好等于一页的时候,只需要处理一次就可以退出for循环了
if(toIndex==totalCount){
break;
}
}
}
}
测试场景
1、总数不足一页
2、总数刚好等于一页
3、总数多余一页
上面三个case都可以正常通过。
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!