Warning: file_put_contents(/datas/wwwroot/jiajiahui/core/caches/caches_template/2/default/show.php): failed to open stream: Permission denied in /datas/wwwroot/jiajiahui/core/libraries/classes/template_cache.class.php on line 55

Warning: chmod(): Operation not permitted in /datas/wwwroot/jiajiahui/core/libraries/classes/template_cache.class.php on line 56
如何使用java实现对ArrayList分页 - 源码之家

如何使用java实现对ArrayList分页

这篇文章将为大家详细讲解有关如何使用java实现对ArrayList分页,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。

java 对ArrayList进行分页

概述

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

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

代码

sublist方法的定义:

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

只需要准确的算出fromIndex和 toIndex即可。

数据准备

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;
      }
    }

  }
}

关于如何使用java实现对ArrayList分页就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。