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]
相关推荐
perseveranceX8 分钟前
插入排序:扑克牌式的排序算法!
c语言·数据结构·插入排序·时间复杂度·排序稳定性
CS创新实验室23 分钟前
典型算法题解:长度最小的子数组
数据结构·c++·算法·考研408
Ialand~3 小时前
深度解析 Rust 的数据结构:标准库与社区生态
开发语言·数据结构·rust
Yupureki5 小时前
从零开始的C++学习生活 18:C语言复习课(期末速通)
c语言·数据结构·c++·学习·visual studio
小兔崽子去哪了5 小时前
数据结构和算法(Python)
数据结构·python
FmZero8 小时前
基于比特位图映射对List<Object>多维度排序
数据结构·list
霸道流氓气质8 小时前
Java中使用Collator实现对象List按照中文姓名属性进行A-Z的排序实现
java·开发语言·list
Mr.H01278 小时前
克鲁斯卡尔(Kruskal)算法
数据结构·算法·图论
熬了夜的程序员8 小时前
【LeetCode】94. 二叉树的中序遍历
数据结构·算法·leetcode·职场和发展·深度优先
熬了夜的程序员8 小时前
【LeetCode】92. 反转链表 II
数据结构·算法·leetcode·链表·职场和发展·排序算法