java对list集合进行分页的四种写法总结
更新时间:2025年05月24日 09:13:01 作者:codingPower
这篇文章主要介绍了java对list集合进行分页的四种写法总结,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
java对list集合进行分页的写法
假设有一个list数组,因为总数过大,在进行查询或者调用外部接口时,需要对其进行分页处理,可以用以下几种方式进行处理
eq:
List<String> bigList=Lists.newArrayList("a","b","c","d","e","f","g","h");1. subList分页【java.util.List.sublist(int fromIndex,int toIndex)】
int pageSize=3;//每页大小
int count=bigList.size();//总list
int totalPage=(int)((count/pageSize)+(count % pageSize >0?1:0));//总页数
for(int i=1;i<=totalPage;i++){
List<String> smallList=bigList.sublist(pageSize*(i-1),Math.min(pageSize*i,count));//截取对应范围数据
System.out.println(smallList.toString());
}2. partition分页【com.google.com.collect.Lists.partition(List list,int size) 】
int pageSize=3;//每页大小
List<List<String>> partitionList=Lists.partition(bigList,pageSize);//进行分页
for(List<String> smallList:partitionList){
System.out.println(smallList.toString());
}3. java8 stream流 分页
int pageSize=3;//每页大小
int count=bigList.size();//总list
int totalPage=(int)((count/pageSize)+(count % pageSize >0?1:0));//总页数
// 使用 Stream 实现分页
for(int i=1;i<=totalPage;i++){
List<String> smallList= bigList.stream()
.skip(PageSize*(i-1)) // 跳过前 PageSize*(i-1) 个元素
.limit(pageSize) // 限制结果数量为 pageSize
.collect(Collectors.toList()); //结果为列表
System.out.println(smallList.toString());
}4. hutool工具类提供的方法ListUtil.split(List list,int size)
实际内部实现还是subList分页
int pageSize=3;//每页大小
List<List<String>> splitList=ListUtil.split(bigList,pageSize);//bigList 需处理的列表,pageSize分页长度
for(List<String> smallList:splitList){
System.out.println(smallList.toString());
}总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
相关文章
SpringBoot3.x嵌入MongoDB进行测试的步骤详解
本文介绍了在 Spring Boot 应用中使用Flapdoodle Embed Mongo进行 MongoDB 测试的方法,包括Embed Mongo 的概念,添加依赖、配置、运行测试的步骤,还列举了其优势如快速启动关闭、环境一致、无需外部依赖等,以及注意事项和结论,需要的朋友可以参考下2024-12-12
HttpClient的RedirectStrategy重定向处理核心机制
这篇文章主要为大家介绍了HttpClient的RedirectStrategy重定向处理核心机制源码解读,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪2023-10-10
java集合 collection-list-LinkedList详解
下面小编就为大家带来一篇java集合 collection-list-LinkedList详解。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧2017-01-01
SpringBoot整合log4j日志与HashMap的底层原理解析
这篇文章主要介绍了SpringBoot整合log4j日志与HashMap的底层原理,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下2021-01-01


最新评论