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)?,那么要實現(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都可以正常通過。
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
相關文章
springboot整合ehcache和redis實現(xiàn)多級緩存實戰(zhàn)案例
這篇文章主要介紹了springboot整合ehcache和redis實現(xiàn)多級緩存實戰(zhàn)案例,從源碼角度分析下多級緩存實現(xiàn)原理,本文通過實例代碼給大家介紹的非常詳細,需要的朋友可以參考下2023-08-08
Spring?MVC中JSON數(shù)據(jù)處理方式實戰(zhàn)案例
Spring MVC是個靈活的框架,返回JSON數(shù)據(jù)的也有很多五花八門的方式,下面這篇文章主要給大家介紹了關于Spring?MVC中JSON數(shù)據(jù)處理方式的相關資料,需要的朋友可以參考下2024-01-01
詳解Java利用ExecutorService實現(xiàn)同步執(zhí)行大量線程
這篇文章主要介紹了Java利用ExecutorService實現(xiàn)同步執(zhí)行大量線程,ExecutorService可以維護我們的大量線程在操作臨界資源時的穩(wěn)定性。2017-03-03
關于fastjson的@JSONField注解的一些問題(詳解)
下面小編就為大家?guī)硪黄P于fastjson的@JSONField注解的一些問題(詳解)。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-02-02

