当前位置: 首页 > news >正文

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

工具类方法

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;}@Overridepublic boolean hasNext() {return currentIndex < list.size();}@Overridepublic List<T> next() {int endIndex = Math.min(currentIndex + batchSize, list.size());List<T> batch = new ArrayList<>(list.subList(currentIndex, endIndex));currentIndex = endIndex;return batch;}
}

测试方法

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

测试结果

[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]
http://www.xdnf.cn/news/359587.html

相关文章:

  • 报错 | vitest中,vue中使用jsx语法,报错:ReferenceError: React is not defined
  • 图上思维:基于知识图的大型语言模型的深层可靠推理
  • YOLOv8 优化:基于 Damo-YOLO 与 DyHead 检测头融合的创新研究
  • Android Framework学习四:init进程实现
  • 矩阵分解——Cholesky分解,LU分解,LDLT分解
  • 华为5.7机考第一题充电桩问题Java代码实现
  • Sourcetree安装使用的详细教程
  • 深入解析网络联通性检测:ping 与 tracert 的原理、用法及实战应用
  • 范式之殇-关系代数与参照完整性在 Web 后台的落寞
  • Linux基础篇命令整合表(大全)
  • Cjson格式解析与接入AI大模型
  • Git标签删除脚本解析与实践:轻松管理本地与远程标签
  • Mysql--基础知识点--91.2--processlist
  • 【LangChain高级系列】LangGraph第一课
  • 开目新一代MOM:AI赋能高端制造的破局之道
  • redhat9 安装pywinrm
  • 制造企业如何选择项目管理软件系统提高项目执行的效率和质量
  • 面试题:请解释Java中的反射机制,并说明其使用场景
  • 2025年科学教育与文化交流国际会议(IACSECE 2025)
  • 【软件设计师:数据】17.数据安全
  • LeetCode 3342.到达最后一个房间的最少时间 II:dijkstra算法(和I一样)
  • 基于OpenCV的人脸识别:EigenFaces算法
  • 变桨系统升级新引擎:CAN转ModbusTCP协议转换技术破解风电数字化困局
  • 在 Spring Boot 中实现动态线程池的全面指南
  • Github 2025-05-09 Java开源项目日报 Top10
  • Error parsing column 10 (YingShou=-99.5 - Double) dapper sqlite
  • 坐席业绩可视化分析工具
  • AbMole:QS-21的作用机理及免疫应用
  • J-Scope的RTT模式
  • 智慧工会服务平台建设方案Word(23页)