import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; public class PageData{ // data private List data; // page info private long pageNum; private long pageSize; private long totalPage; private long totalSize; public PageData(List data, long pageSize) { if (data == null) { throw new RuntimeException("data could not be null"); } if (pageSize <= 0) { throw new RuntimeException("page size could not less than 0"); } this.data = data; this.pageSize = pageSize; this.totalSize = data.size(); this.pageNum = 0; this.totalPage = totalSize % pageSize == 0 ? totalSize / pageSize : totalSize / pageSize + 1; } public boolean hasNext() { return pageNum < totalPage; } public List nextPage() { if (hasNext()) { return page(++pageNum); } throw new RuntimeException("out of bounds"); } public boolean hasLast() { return pageNum > 1; } public List lastPage() { if (hasLast()) { return page(--pageNum); } throw new RuntimeException("out of bounds of page data"); } public List page(long page) { return page(page, this.pageSize); } public List page(long page, long pageSize) { if (page <= 0 || pageSize <= 0) { throw new RuntimeException("page or page size could not less than 0"); } return data.stream() .skip((page - 1) * pageSize) .limit(pageSize) .collect(Collectors.toList()); } public static void main(String[] args) { // example for this List list = new ArrayList<>(); for (int i = 0; i < 100; i++){ list.add(i); } PageData pageData = new PageData<>(list, 30); while (pageData.hasNext()){ List currentPageData = pageData.nextPage(); System.out.println(currentPageData.size()); // 30, 30, 30, 10 } } }



