List<T>中每次取固定长度的数据

工具类方法

java 复制代码
package org.common.util;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * 批处理取值组件
 * @param <T>
 */
public class BatchIterator<T> implements Iterator<List<T>> {
    private final List<T> list;
    private final int batchSize;
    private int currentIndex;

    public BatchIterator(List<T> list, int batchSize) {
        this.list = list;
        this.batchSize = batchSize;
        this.currentIndex = 0;
    }

    @Override
    public boolean hasNext() {
        return currentIndex < list.size();
    }

    @Override
    public List<T> next() {
        int endIndex = Math.min(currentIndex + batchSize, list.size());
        List<T> batch = new ArrayList<>(list.subList(currentIndex, endIndex));
        currentIndex = endIndex;
        return batch;
    }
}

测试方法

java 复制代码
package org.common.util;

import org.common.util.BatchIterator;

import java.util.ArrayList;
import java.util.List;

public class BatchIteratorTest {
    public static List<Integer> setListData(){
        List<Integer> tmpList =new ArrayList<>();
        for (int i = 0; i < 100; i++) {
            tmpList.add(i);
        }
        return tmpList;
    }
    public static void main(String[] args) {
        // 创建一个批处理迭代器,每次取500条数据
        BatchIterator<Integer> batchIterator = new BatchIterator<>(setListData(), 20);
        while (batchIterator.hasNext()) {
            List<Integer> tempList = batchIterator.next();
            System.out.println(tempList);
        }
    }
}

测试结果

text 复制代码
[0, 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, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39]
[40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59]
[60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79]
[80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99]
相关推荐
如竟没有火炬30 分钟前
LRU缓存——双向链表+哈希表
数据结构·python·算法·leetcode·链表·缓存
爱吃生蚝的于勒1 小时前
【Linux】零基础学会Linux之权限
linux·运维·服务器·数据结构·git·算法·github
爱编程的化学家2 小时前
代码随想录算法训练营第27天 -- 动态规划1 || 509.斐波那契数列 / 70.爬楼梯 / 746.使用最小花费爬楼梯
数据结构·c++·算法·leetcode·动态规划·代码随想录
DN金猿5 小时前
java8提取list中对象有相同属性值的对象或属性值
java·list·stream·java8
一只鱼^_5 小时前
力扣第470场周赛
数据结构·c++·算法·leetcode·深度优先·动态规划·启发式算法
Univin12 小时前
C++(10.4)
开发语言·数据结构·c++
Jayden_Ruan19 小时前
C++十进制转二进制
数据结构·c++·算法
Haooog19 小时前
98.验证二叉搜索树(二叉树算法题)
java·数据结构·算法·leetcode·二叉树
lixinnnn.21 小时前
贪心:火烧赤壁
数据结构·c++·算法