对ArrayList进行分页

来源:互联网 发布:可延迟服务器调度算法 编辑:程序博客网 时间:2024/05/16 09:36

概述


系统与系统之间的交互,通常是使用接口的形式。假设B系统提供了一个批量的查询接口,限制每次只能查询50条数据,而我们实际需要查询500条数据,这个时候可以对这500条数据做分批操作,分10次调用B系统的批量接口。

如果B系统的查询接口是使用List作为入参,那么要实现分批调用的话,可以利用ArrayListsubList方法来处理。


代码


sublist方法的定义:

    List<E> subList(int fromIndex, int toIndex);

只需要准确的算出fromIndextoIndex即可。

数据准备

public class TestArrayList {    public static void main(String[] args) {        List<Long> datas = Arrays.asList(new Long [] {1L,2L,3L,4L,5L,6L,7L});    }}

分页算法

import java.util.Arrays;import java.util.List;public class TestArrayList {    private static final Integer PAGE_SIZE = 3;    public static void main(String[] args) {        List<Long> datas = Arrays.asList(new Long [] {1L,2L,3L,4L,5L,6L,7L,8L});        //总记录数        Integer totalCount = datas.size();        //分多少次处理        Integer requestCount = totalCount / PAGE_SIZE;        for (int i = 0; i <= requestCount; i++) {            Integer fromIndex = i * PAGE_SIZE;            //如果总数少于PAGE_SIZE,为了防止数组越界,toIndex直接使用totalCount即可            int toIndex = 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都可以正常通过。

3 0