分批次处理List
因为调用第三方接口,传入的参数有数量的限制要求。所以需要对传入的参数进行数量上的处理。
附上方法代码:
/**
* 通过subList来处理
*
* 2017年10月27日上午2:06:24
* @param sourList准备处理的数据List<Object>
* @param batchCount准备以多少数目去处理,比如20,就是20一批处理
* @parameter
* void
*
*/
public static void dealBySubList(List<Object> sourList, int batchCount){
int sourListSize = sourList.size();
int subCount = sourListSize%batchCount==0 ? sourListSize/batchCount : sourListSize/batchCount+1;
int startIndext = 0;
int stopIndext = 0;
if(sourListSize >= batchCount){
stopIndext = batchCount;
}else{
stopIndext = sourListSize;
}
for(int i=0;i<subCount;i++){
List<Object> tempList = new ArrayList<Object>(sourList.subList(startIndext, stopIndext));
printList(tempList);
startIndext = startIndext + batchCount;
stopIndext = stopIndext + batchCount;
if(i == subCount-2 && stopIndext != sourListSize){
stopIndext = sourListSize;
}
}
}
测试代码:
public static void main(String[] args) {
List<Object> list = new ArrayList<Object>();
for (int i = 0; i < 10; i++) {
list.add(String.valueOf(i));
}
long start = System.nanoTime();
dealBySubList(list, 20);
long end = System.nanoTime();
System.out.println("The elapsed time :" + (end-start));
}
sourList和batchCount的关系:
1,sourList = batchCount
2,sourList > batchCount
3,sourList < batchCount
经过测试:运行没有问题,对这个方法修改就能变成自己需要的方法,本质上是分页的思想。