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());
}总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
相关文章
解决IDEA报错war exploded is not valid问题
在使用IntelliJ IDEA时遇到'[projectname]warexploded'无效的问题,可以通过清除项目列表、重新导入项目和配置新的Tomcat来解决,确保在Tomcat配置中,将ApplicationContext修改为仅包含一个'/',这一方法或许能帮助遇到相似问题的开发者2024-09-09
SpringBoot跨域Access-Control-Allow-Origin实现解析
这篇文章主要介绍了SpringBoot跨域Access-Control-Allow-Origin实现解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下2019-12-12
浅谈spring的重试机制无效@Retryable@EnableRetry
这篇文章主要介绍了浅谈spring的重试机制无效@Retryable@EnableRetry,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧2020-09-09


最新评论