Java 自定義 List 分頁工具
PS: T可修改为对应的实体
rt com.google.common.collect.Lists;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
/**
* @ClassName: MyPageHelper
* @Descripution: List<T>分頁工具
**/
public class MyPageHelper<T> {
public List<T> splitList(List<T> list, int page, int pageSize) {
if (page <= 0) {
throw new IllegalArgumentException("MyPageHelper error: page number cannot be less than or equal to zero");
}
if (pageSize <= 0) {
throw new IllegalArgumentException("MyPageHelper error: page size cannot be less than or equal to zero");
}
int fromIndex = (page - 1) * pageSize;
if (fromIndex >= list.size()) {
return Collections.emptyList();
}
int toIndex = fromIndex + pageSize;
if (toIndex > list.size()) {
toIndex = list.size();
}
List<List<T>> partition = Lists.partition(list.subList(fromIndex, toIndex), pageSize);
return partition.isEmpty() ? null : partition.get(0);
}
// 測試
public static void main(String[] args) {
// 使用方法
MyPageHelper<Integer> paginationHelper = new MyPageHelper<>();
List<Integer> fullList = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
int page = 3; // 第二頁
int pageSize = 4; // 每頁3條記錄
List<Integer> pages = paginationHelper.splitList(fullList, page, pageSize);
System.out.println(pages);
}
设置 显示第三页数据,数据条数为4
int page = 3; // 第3頁
int pageSize = 4; // 每頁4條記錄
执行结果:
[9, 10]
END