Java 如何在列表上实现分页?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19688235/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to implement pagination on a list?
提问by membersound
Is there any library that can be used to implement paging for a list?
有没有可以用来实现列表分页的库?
Let' assume I have a space of 10 lines, and the user can select if he wants to scroll forward or backward by page (thus +- 10 items). This might eg be controlled by -1, 0, +1
.
假设我有 10 行的空间,并且用户可以选择是要向前还是向后滚动页面(因此 +- 10 个项目)。这可能例如由控制-1, 0, +1
。
This is probably much work to build a class that prevents scrolling backward/forward if there are not enough items to display, and to self-save the state on which page the user is currently.
如果没有足够的项目可显示,构建一个防止向后/向前滚动的类,以及自我保存用户当前所在页面的状态,这可能是很多工作。
So is there anything?
所以有什么吗?
采纳答案by pscuderi
I've solved this before. I made a static getPages method that breaks a generic collection into a list of pages (which are also lists). I've provided the code below.
我以前解决过这个问题。我创建了一个静态 getPages 方法,它将一个通用集合分解为一个页面列表(它们也是列表)。我已经提供了下面的代码。
public static <T> List<List<T>> getPages(Collection<T> c, Integer pageSize) {
if (c == null)
return Collections.emptyList();
List<T> list = new ArrayList<T>(c);
if (pageSize == null || pageSize <= 0 || pageSize > list.size())
pageSize = list.size();
int numPages = (int) Math.ceil((double)list.size() / (double)pageSize);
List<List<T>> pages = new ArrayList<List<T>>(numPages);
for (int pageNum = 0; pageNum < numPages;)
pages.add(list.subList(pageNum * pageSize, Math.min(++pageNum * pageSize, list.size())));
return pages;
}
回答by kisna
Minor optimization, if you don't really want to create any new list at all.
小优化,如果你真的不想创建任何新列表。
/**
* returns a view (not a new list) of the sourceList for the
* range based on page and pageSize
* @param sourceList
* @param page, page number should start from 1
* @param pageSize
* @return
*/
public static <T> List<T> getPage(List<T> sourceList, int page, int pageSize) {
if(pageSize <= 0 || page <= 0) {
throw new IllegalArgumentException("invalid page size: " + pageSize);
}
int fromIndex = (page - 1) * pageSize;
if(sourceList == null || sourceList.size() < fromIndex){
return Collections.emptyList();
}
// toIndex exclusive
return sourceList.subList(fromIndex, Math.min(fromIndex + pageSize, sourceList.size()));
}