欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

java 對ArrayList進行分頁實例代碼

 更新時間:2017年02月17日 14:11:17   投稿:lqh  
這篇文章主要介紹了java 對ArrayList進行分頁實例代碼的相關資料,需要的朋友可以參考下

java 對ArrayList進行分頁

概述

系統(tǒng)與系統(tǒng)之間的交互,通常是使用接口的形式。假設B系統(tǒng)提供了一個批量的查詢接口,限制每次只能查詢50條數(shù)據(jù),而我們實際需要查詢500條數(shù)據(jù),這個時候可以對這500條數(shù)據(jù)做分批操作,分10次調(diào)用B系統(tǒng)的批量接口。

如果B系統(tǒng)的查詢接口是使用List作為入?yún)ⅲ敲匆獙崿F(xiàn)分批調(diào)用的話,可以利用ArrayList的subList方法來處理。

代碼

sublist方法的定義:

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

只需要準確的算出fromIndex和 toIndex即可。

數(shù)據(jù)準備

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

    //總記錄數(shù)
    Integer totalCount = datas.size();

    //分多少次處理
    Integer requestCount = totalCount / PAGE_SIZE;

    for (int i = 0; i <= requestCount; i++) {
      Integer fromIndex = i * PAGE_SIZE;
      //如果總數(shù)少于PAGE_SIZE,為了防止數(shù)組越界,toIndex直接使用totalCount即可
      int toIndex = Math.min(totalCount, (i + 1) * PAGE_SIZE);
      List<Long> subList = datas.subList(fromIndex, toIndex);
      System.out.println(subList);
      //總數(shù)不到一頁或者剛好等于一頁的時候,只需要處理一次就可以退出for循環(huán)了
      if (toIndex == totalCount) {
        break;
      }
    }

  }
}

測試場景

1、總數(shù)不足一頁
2、總數(shù)剛好等于一頁
3、總數(shù)多余一頁

上面三個case都可以正常通過。

感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!

相關文章

最新評論