java 内存分页实现以及list的stream流
package com.how2java.springboot; import org.springframework.util.CollectionUtils; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; public class MemoryPagination { public static <T> List<T> pagination(List<T> records, int pageNum, int pageSize) { if (CollectionUtils.isEmpty(records)) { return Collections.emptyList(); } int totalCount = records.size(); int remainder = totalCount % pageSize; int pageCount = (remainder > 0) ? totalCount / pageSize + 1 : totalCount / pageSize; if (remainder == 0) { return records.stream().skip((pageNum - 1) * pageSize).limit(pageSize).collect(Collectors.toList()); } else { if (pageNum == pageCount) { return records.stream().skip((pageNum - 1) * pageSize).limit(totalCount).collect(Collectors.toList()); } else { return records.stream().skip((pageNum - 1) * pageSize).limit(pageSize).collect(Collectors.toList()); } } } public static void main(String[] args) { ArrayList<String> myList = new ArrayList(); Collections.addAll(myList, "q", "w", "e", "r"); List<String> pagination = pagination(myList, 2, 2); for (String i : pagination) { System.out.println(i); } } }
首先将list进行stream化,然后就是skip去除前几个数据,限制多少个结束,最后列表化
stream的常用方法
filter 过滤 .filter(x -> x.y == 20) 截取x的y等于20的数据
sorted 排序, 实现了 Comparable 接口 可以传递自己的排序规则
sorted((p1, p2) -> p1.getAge() - p2.getAge()
skip(long n)
删除前n个元素
limit(long n)
返回前n个元素
map(T -> R)
将流中的每一个元素 T 映射为 R(类似类型转换)
map(Person::getName)
collect(toList()) 可以把流转换为 List 类型
https://blog.csdn.net/fengfengchen95/article/details/102621844