目录
1. 定义page类
import java.util.AbstractList;
import java.util.ArrayList;
import java.util.List;
/**
* @version 1.0
* @Author Lix
* @Date 2022/7/20 18:34
* @desc Another day of coding
*/
public class Page<E> extends AbstractList<E> {
private int totalPages;
private long totalElements;
private int numberOfElements;
private int size;
private int number;
private List<E> content;
public Page() {
this.content = new ArrayList();
}
public void setTotalPages(int totalPages) {
this.totalPages = totalPages;
}
public void setTotalElements(long totalElements) {
this.totalElements = totalElements;
}
public void setNumberOfElements(int numberOfElements) {
this.numberOfElements = numberOfElements;
}
public void setSize(int size) {
this.size = size;
}
public void setNumber(int number) {
this.number = number;
}
public void setContent(List<E> content) {
this.content = content;
}
public int getTotalPages() {
return totalPages;
}
public long getTotalElements() {
return totalElements;
}
public int getNumberOfElements() {
return numberOfElements;
}
public int getSize() {
return size;
}
public int getNumber() {
return number;
}
public List<E> getContent() {
return content;
}
@Override
public E get(int index) {
return this.content.get(index);
}
@Override
public int size() {
return this.content.size();
}
}
2. PageUtiL类
import cn.hutool.db.PageResult;
import org.springframework.util.CollectionUtils;
import java.util.List;
/**
* @version 1.0
* @Author Lix
* @Date 2022/7/20 18:14
* @desc Another day of coding
*/
public class PageUtil {
public static <T> Page<T> pageMethod(List<T> list, PageResult pageRequest) {
Page<T> result = new Page<T>();
if (CollectionUtils.isEmpty(list)){
return result;
}
int start = pageRequest.getPage() * pageRequest.getPageSize();
int end = (pageRequest.getPage() + 1) * pageRequest.getPageSize();
if (list.size() < end) {
end = list.size();
}
int total = list.size();
List<T> subList = list.subList(start, end);
result.setTotalElements((long) total);
result.setSize(pageRequest.getPageSize());
result.setNumber(pageRequest.getPage());
result.setTotalPages((total - 1) / pageRequest.getPageSize() + 1);
result.setNumberOfElements(subList.size());
result.setContent(subList);
return result;
}
}