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]
相关推荐
yuuki2332333 分钟前
【C语言&数据结构】二叉树的链式递归
c语言·数据结构·后端
前端小L4 小时前
图论专题(十五):BFS的“状态升维”——带着“破壁锤”闯迷宫
数据结构·算法·深度优先·图论·宽度优先
福尔摩斯张9 小时前
Axios源码深度解析:前端请求库设计精髓
c语言·开发语言·前端·数据结构·游戏·排序算法
思成不止于此10 小时前
【C++ 数据结构】二叉搜索树:原理、实现与核心操作全解析
开发语言·数据结构·c++·笔记·学习·搜索二叉树·c++40周年
爪哇部落算法小助手11 小时前
每日两题day50
数据结构·c++·算法
司铭鸿13 小时前
图论中的协同寻径:如何找到最小带权子图实现双源共达?
linux·前端·数据结构·数据库·算法·图论
小年糕是糕手14 小时前
【C++】C++入门 -- 输入&输出、缺省参数
c语言·开发语言·数据结构·c++·算法·leetcode·排序算法
chbmvdd15 小时前
week5题解
数据结构·c++·算法
vir0215 小时前
小齐的技能团队(dp)
数据结构·c++·算法·图论
_w_z_j_16 小时前
数组中的最长连续子序列
数据结构·算法