大集合分批操作工具


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");
        }


    }


}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值