Java使用subList对List分页
package org.utils;
import java.util.ArrayList;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.databind.ObjectMapper;
public class CustomPage<T> {
private Integer pageNo;
private Integer total;
private Integer pages;
@JsonIgnore
private Integer pageSize;
private List<T> records;
public CustomPage(List<T> list,Integer pageNo,Integer pageSize){
this.pageNo = pageNo;
this.pageSize = pageSize;
this.total = list.size();
boolean full = total % pageSize == 0;
if(!full){
this.pages = total/pageSize + 1;
}else{
this.pages = total/pageSize;
}
int fromIndex = 0;
int toIndex = 0;
fromIndex = pageNo*pageSize-pageSize;
if(pageNo == 0){
throw new ArithmeticException("第0页无法展示");
}else if(pageNo>pages){
list = new ArrayList<>();
}else if(pageNo == pages){
toIndex = total;
}else{
toIndex = pageNo*pageSize;
}
if(list.size() == 0){
this.records = list;
}else{
this.records = list.subList(fromIndex, toIndex);
}
}
public Integer getPageNo() {
return pageNo;
}
public void setPageNo(Integer pageNo) {
this.pageNo = pageNo;
}
public Integer getTotal() {
return total;
}
public void setTotal(Integer total) {
this.total = total;
}
public Integer getPages() {
return pages;
}
public void setPages(Integer pages) {
this.pages = pages;
}
public Integer getPageSize() {
return pageSize;
}
public void setPageSize(Integer pageSize) {
this.pageSize = pageSize;
}
public List<T> getRecords() {
return records;
}
public void setRecords(List<T> list) {
this.records = list;
}
}
调用
CustomPage<Bean> customPage = new CustomPage<>(Beanlist, pageNo, pageSize);