概述
系統(tǒng)與系統(tǒng)之間的交互,通常是使用接口的形式。假設(shè)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方法的定義:
1
|
List<E> subList( int fromIndex, int toIndex); |
只需要準確的算出fromIndex和 toIndex即可。
數(shù)據(jù)準備
1
2
3
4
5
6
|
public class TestArrayList { public static void main(String[] args) { List<Long> datas = Arrays.asList( new Long [] {1L,2L,3L,4L,5L,6L,7L}); } } |
分頁算法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
|
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都可以正常通過。
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
原文鏈接:http://blog.csdn.net/linsongbin1/article/details/54317583