手动对List内元素进行分页处理
2019-02-18 本文已影响0人
iMUST_Clown
本文内容
- 手动对List内元素进行分页处理
- 对分页查询有个更立体的认识
前置知识
- 三目运算
- 集合
- eclipse/My eclipse/IDEA 工具
环境
· JDK 1.8
具体源码
实体类
public class Paging {
private Integer totalNum;
private Integer totalPage;
private Integer pageSize;
private Integer pageIndex;
private Integer queryIndex;
public Paging subPaging(Integer totalNum, Integer pageSize, Integer pageIndex) {
Paging page = new Paging();
page.setTotalNum(totalNum);
Integer totalPage = totalNum % pageSize == 0 ? totalNum / pageSize : totalNum / pageSize + 1;
page.setTotalPage(totalPage);
page.setPageIndex(pageIndex + 1);
page.setPageSize(pageSize);
page.setQueryIndex(pageSize * pageIndex);
return page;
}
public Integer getTotalNum() {
return totalNum;
}
public void setTotalNum(Integer totalNum) {
this.totalNum = totalNum;
}
public Integer getTotalPage() {
return totalPage;
}
public void setTotalPage(Integer totalPage) {
this.totalPage = totalPage;
}
public Integer getPageSize() {
return pageSize;
}
public void setPageSize(Integer pageSize) {
this.pageSize = pageSize;
}
public Integer getPageIndex() {
return pageIndex;
}
public void setPageIndex(Integer pageIndex) {
this.pageIndex = pageIndex;
}
public Integer getQueryIndex() {
return queryIndex;
}
public void setQueryIndex(Integer queryIndex) {
this.queryIndex = queryIndex;
}
}
测试类
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class testPaging {
public static void main(String[] args) {
List<String> list = test();
for (String string : list) {
System.out.println(string);
}
}
public static List<String> test() {
List<String> strs = new ArrayList<String>();
String str1 = "1";
String str2 = "2";
String str3 = "3";
String str4 = "4";
String str5 = "5";
String str6 = "6";
String str7 = "7";
String str8 = "8";
String str9 = "9";
String str10 = "10";
strs.add(str1);
strs.add(str2);
strs.add(str3);
strs.add(str4);
strs.add(str5);
strs.add(str6);
strs.add(str7);
strs.add(str8);
strs.add(str9);
strs.add(str10);
int totalNum = strs.size();
int pageSize = 3;
int pageIndex = 0;
Paging paging = new Paging().subPaging(totalNum, pageSize, pageIndex);
int fromIndex = paging.getQueryIndex();
int totalIndex = 0;
if (fromIndex + paging.getPageIndex() >= totalNum) {
totalIndex = totalNum;
} else {
totalIndex = fromIndex + paging.getPageSize();
}
if (fromIndex > totalIndex) {
return Collections.emptyList();
}
return strs.subList(fromIndex, totalIndex);
}
}
以下为测试结果:
int totalNum = strs.size();
int pageSize = 3;
int pageIndex = 0;
测试结果1
int totalNum = strs.size();
int pageSize = 3;
int pageIndex = 1;
测试结果2
int totalNum = strs.size();
int pageSize = 5;
int pageIndex = 1;
测试结果3