概述
系統與系統之間的交互,通常是使用接口的形式。假設B系統提供了一個批量的查詢接口,限制每次只能查詢50條數據,而我們實際需要查詢500條數據,這個時候可以對這500條數據做分批操作,分10次調用B系統的批量接口。
如果B系統的查詢接口是使用List作為入參,那么要實現分批調用的話,可以利用ArrayList的subList方法來處理。
代碼
sublist方法的定義:
1
|
List<E> subList( int fromIndex, int toIndex); |
只需要準確的算出fromIndex和 toIndex即可。
數據準備
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}); //總記錄數 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都可以正常通過。
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
原文鏈接:http://blog.csdn.net/linsongbin1/article/details/54317583