当前位置: 首页 > 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.dtcms.com/a/181004.html

相关文章:

  • 数据结构与算法—顺序表和链表(1)
  • 互联网大厂Java求职面试:基于RAG的智能问答系统设计与实现
  • N6715C 基础型定制配置直流电源分析仪
  • 升级 Azure Kubernetes 服务群集的关键注意事项
  • C#学习——继承、封装、多态
  • 软件工程之面向对象分析深度解析
  • 《软件项目经济性论证报告模板:全面解析与策略建议》
  • 排序算法-希尔排序
  • 移动IP与手机移动数据流量的概念、原理、区别与联系
  • 手写 vue 源码 === ref 实现
  • 开源数字人框架 AWESOME-DIGITAL-HUMAN 技术解析与应用指南
  • OpenHarmony平台驱动开发(十),MMC
  • 【优选算法】C++双指针问题
  • 基于扩展卡尔曼滤波(EKF)目标轨迹算法仿真实例
  • 《深挖Java中的对象生命周期与垃圾回收机制》
  • PECVD 和 半导体等离子体刻蚀 工艺的异同点
  • 【Pandas】pandas DataFrame all
  • Java中关于多态的总结
  • 【Python-Day 11】列表入门:Python 中最灵活的数据容器 (创建、索引、切片)
  • 已解决:安卓刚打开新项目的时候,会下载该项目要求的sdk gradle,开了科学上网也慢
  • 《Spring Boot 3.0全新特性详解与实战案例》
  • 使用 NSSM 安装 Tomcat 11.0.6 为 Windows 服务
  • QT聊天项目DAY10
  • 【Golang】gin框架动态更新路由
  • WebRTC流媒体传输协议RTP点到点传输协议介绍,WebRTC为什么使用RTP协议传输音视频流?
  • 电压取样端口静电浪涌防护方案 之6TS Series瞬态抑制器TVS
  • 2025年社交APP安全防御指南:抵御DDoS与CC攻击的实战策略
  • 【免杀】C2免杀 | 概念篇
  • Python 爬虫基础入门教程(超详细)
  • 2025数字孪生技术全景洞察:从工业革命到智慧城市的跨越式发展