import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
/**
* 对一个大集合进行数据分页
* 非线程安全的类
* @param <T>
* @author zhshl
* @date 2020-04-20
*/
public class BatchHelper<T> implements Iterable<List<T>> {
private final List<T> source ;
/**
* 将当前集合按多大一批进行拆分
*/
private final int size;
/**
* 目前的索引值
*/
private int currentIndex = 1;
private int totalPage ;
public BatchHelper(List<T> source,int size) {
this.source = source;
this.size = size;
totalPage = (int) Math.ceil( source.size() *1.0/size);
}
@Override
public Iterator<List<T>> iterator() {
return new ListItr();
}
private class ListItr implements Iterator<List<T>>{
@Override
public boolean hasNext() {
return currentIndex <= totalPage;
}
@Override
public List<T> next() {
List<T> list = null;
if(currentIndex == totalPage){
list = source.subList((currentIndex - 1) * size, source.size());
}else{
list = source.subList((currentIndex - 1) * size,currentIndex*size);
}
currentIndex++;
return list;
}
}
public static void main(String[] args) {
List<Integer> list = new ArrayList<>();
list.add(1);
list.add(2);
list.add(3);
list.add(4);
list.add(5);
list.add(6);
list.add(7);
list.add(8);
list.add(9);
list.add(10);
BatchHelper<Integer> lists = new BatchHelper<>(list, 3);
Iterator<List<Integer>> iterator = lists.iterator();
while(iterator.hasNext()){
List<Integer> next = iterator.next();
System.out.println("1");
}
}
}
大集合分批操作工具
最新推荐文章于 2024-05-17 21:33:19 发布