ArrayList分页

188 阅读1分钟

# 如何使用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即可      i
				nt toIndex = Math.min(totalCount, (i + 1) * PAGE_SIZE);      
				List<Long> subList = datas.subList(fromIndex, toIndex);      
				System.out.println(subList);      //总数不到一页或者刚好等于一页的时候,只需要处理一次就可以退出for循环了      
				if (toIndex == totalCount) {
				    break;      
					}    
				}  
			}
		}