JpaPageUtils.java 工具类
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
public class JpaPageUtils {
private static Integer defaultPageSize = 10;
public static <T> Page<T> listToPage(List<T> list, int pageNo) {
PageRequest pageable = PageRequest.of(pageNo - 1, defaultPageSize);
return getPage(list, pageable);
}
public static <T> Page<T> listToPage(List<T> list, int pageNo, int pageSize) {
PageRequest pageable = PageRequest.of(pageNo - 1, pageSize);
return getPage(list, pageable);
}
public static <T> Page<T> getPage(List<T> list) {
PageRequest pageable = PageRequest.of(0, defaultPageSize);
return getPage(list, pageable);
}
public static <T> Page<T> getPage(List<T> list, Pageable pageable) {
// 第n页起始值
int pageStart = pageable.getPageNumber() * pageable.getPageSize();
// 第n页期望结尾值
int expectPageEnd = pageStart + pageable.getPageSize() - 1;
return Optional.of(list.size()).filter(size -> size >= pageStart)
.map(size -> getRealSubList(pageStart, expectPageEnd, list, pageable))
.orElseGet(() -> getEmptySubList(list, pageable));
}
private static <T> PageImpl<T> getRealSubList(int pageStart, int expectPageEnd, List<T> list, Pageable pageable) {
int realPageEnd = (list.size() > expectPageEnd) ? expectPageEnd + 1 : list.size();
return new PageImpl<>(list.subList(pageStart, realPageEnd), pageable, list.size());
}
private static <T> PageImpl<T> getEmptySubList(List<T> list, Pageable pageable) {
return new PageImpl<>(new ArrayList(), pageable, list.size());
}
}