springboot list 转为page
时间: 2023-07-01 11:16:46 浏览: 58
将一个List转换为Page对象需要以下步骤:
1. 创建Pageable对象。Pageable对象包含了分页的信息,如页码、每页数据量等等。可以使用PageRequest.of方法创建一个Pageable对象。
```java
Pageable pageable = PageRequest.of(pageNumber, pageSize);
```
2. 将List和Pageable对象传入PageImpl构造函数,创建Page对象。
```java
Page<T> page = new PageImpl<T>(list, pageable, list.size());
```
完整代码如下:
```java
public <T> Page<T> listToPage(List<T> list, int pageNumber, int pageSize) {
Pageable pageable = PageRequest.of(pageNumber, pageSize);
int startIndex = pageable.getPageNumber() * pageable.getPageSize();
int endIndex = (startIndex + pageable.getPageSize()) > list.size() ? list.size() : (startIndex + pageable.getPageSize());
return new PageImpl<T>(list.subList(startIndex, endIndex), pageable, list.size());
}
```
其中,startIndex和endIndex是根据Pageable对象计算出来的分页查询起始和结束位置。最后,将List和Pageable对象传入PageImpl构造函数,创建Page对象。
注意:这种方式适用于静态的List对象,如果数据是从数据库中查询出来的,请使用Spring Data JPA提供的分页功能。
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)