1. 程式人生 > >對ArrayList進行分頁

對ArrayList進行分頁

概述

系統與系統之間的互動,通常是使用介面的形式。假設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都可以正常通過。