/*
* @(#)BatchIterator.java 2014-9-13
*
* Copy Right@ uuola
*/
package com.uuola.commons;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
/**
* <pre>
* 集合分批迭代
* @author tangxiaodong
* 创建日期: 2014-9-13
* </pre>
*/
public class BatchIterator<E> implements Iterator<List<E>> {
/**
* 当前的批次集合返回的元素个数
*/
private int batchSize;
private List<E> srcList;
private int index = 0;
private List<E> result;
private int size = 0;
public BatchIterator(List<E> srcList, int batchSize) {
if (0 >= batchSize) {
throw new RuntimeException(
"Please do not be set less than or equal to '0' for GenericBatchIterator's batchSize !");
}
this.batchSize = batchSize;
this.srcList = srcList;
this.size = null == srcList ? 0 : srcList.size();
result = new ArrayList<E>(batchSize);
}
@Override
public boolean hasNext() {
return index < size;
}
@Override
public List<E> next() {
result.clear();
for (int i = 0; i < batchSize && index < size; i++) {
result.add(srcList.get(index++));
}
return result;
}
/**
* 暂不支持移除子集合方法
*/
@Override
public void remove() {
throw new UnsupportedOperationException();
}
}
使用方法:
.....
private static void test4() {
// TODO Auto-generated method stub
List<Integer> numbox = new ArrayList<Integer>();
Collections.addAll(numbox, 1, 2,3,4,5,6,7);
Iterator<List<Integer>> batchIter = new BatchIterator(numbox, 8);
while (batchIter.hasNext()) {
List<Integer> nums = batchIter.next();
System.out.println(nums);
}
System.out.println("test4 end --");
}
......