首页
点滴
当list数据量过大时,分批处理数据的小示例
#### 方式一:自己手动实现 ``` // 定义集合数据 List
list = Arrays.asList(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19); int totalCount = list.size(); // 总记录数 int eachQueryNum = 4; // 每批查询记录数 // 计算页数 int pageNum = totalCount % eachQueryNum == 0 ? totalCount / eachQueryNum : (totalCount / eachQueryNum) + 1; for (int i = 0; i < pageNum; i++) { int start = i * eachQueryNum; int end = (i + 1) * eachQueryNum <= list.size() ? (i + 1) * eachQueryNum : list.size(); List
listTemp = new ArrayList<>(list.subList(start, end)); System.out.println(listTemp); } // 输出结果: [1, 2, 3, 4] [5, 6, 7, 8] [9, 10, 11, 12] [13, 14, 15, 16] [17, 18, 19] ``` #### 方式二:引入Hutool工具包,通过工具类分批 ```xml
cn.hutool
hutool-all
5.8.0.M2
``` ``` int eachQueryNum = 4; // 每批查询记录数 // 定义集合数据 List
list = Arrays.asList(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19); // 调用ListUtil工具类的split方法实现分批 List
> splitList = ListUtil.split(list, eachQueryNum); for (List
integers : splitList) { System.out.println(integers); } // 输出结果: [1, 2, 3, 4] [5, 6, 7, 8] [9, 10, 11, 12] [13, 14, 15, 16] [17, 18, 19] ``` #### 方式三:引入commons-collections4工具包,通过工具类分批 ```xml
org.apache.commons
commons-collections4
4.4
``` ``` int eachQueryNum = 4; // 每批查询记录数 // 定义集合数据 List
list = Arrays.asList(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19); // 调用ListUtils工具类的partition方法实现分批 List
> partitionList = ListUtils.partition(list, eachQueryNum); for (List
integers : partitionList) { System.out.println(integers); } // 输出结果: [1, 2, 3, 4] [5, 6, 7, 8] [9, 10, 11, 12] [13, 14, 15, 16] [17, 18, 19] ``` #### 方式四:引入guava工具包,通过工具类分批 ```xml
com.google.guava
guava
31.1-jre
``` ``` int eachQueryNum = 4; // 每批查询记录数 // 定义集合数据 List
list = Arrays.asList(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19); // 调用Lists工具类的partition方法实现分批 List
> partitionList = Lists.partition(list, eachQueryNum); for (List
integers : partitionList) { System.out.println(integers); } // 输出结果: [1, 2, 3, 4] [5, 6, 7, 8] [9, 10, 11, 12] [13, 14, 15, 16] [17, 18, 19] ```
博客分类
源码解析 (1)
多线程 (5)
Java (10)
Linux (8)
Docker (9)
SpringBoot (14)
微服务 (1)
Redis (15)
MySQL (7)
VMware (3)
Nginx (15)
MyBatis (2)
RabbitMQ (1)
Git (7)
工具类 (12)
前端 (3)
友情链接
layui
© 2020-2025 www.chenhuazhan.com All Rights Reserved 备案号:
桂ICP备17004487号-1
粤公网安备44030002005146