java java分页实用程序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12214894/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 08:04:29  来源:igfitidea点击:

java paging util

java

提问by Alstresh

I have List of Object. I need to do pagination.
The input parameters are the maximum number object per Page and Page number.

我有对象列表。我需要做分页。
输入参数是每页的最大数量对象和页码。

For example input list = ("a", "b", "c", "d", "e", "f")
The maximum number per Page is 2 Page number is 2 Result = ("c", "d")

例如输入 每页list = ("a", "b", "c", "d", "e", "f")
的最大数量为 2 页数为 2 结果 = ("c", "d")

Are there any ready-made classes(libs) to do this? For example Apache project or so on.

有没有现成的类(库)来做到这一点?例如Apache项目等等。

回答by Christian Kuetbach

int sizePerPage=2;
int page=2;

int from = Math.max(0,page*sizePerPage);
int to = Math.min(list.size(),(page+1)*sizePerPage)

list.subList(from,to)

回答by Walery Strauch

With Java 8 steams:

使用 Java 8 蒸汽:

list.stream()
  .skip(page * size)
  .limit(size)
  .collect(Collectors.toCollection(ArrayList::new));

回答by hsz

Try with:

尝试:

int page    = 1; // starts with 0, so we on the 2nd page
int perPage = 2;

String[] list    = new String[] {"a", "b", "c", "d", "e", "f"};
String[] subList = null;

int size = list.length;
int from = page * perPage;
int to   = (page + 1) * perPage;
    to   = to < size ? to : size;

if ( from < size ) {
    subList = Arrays.copyOfRange(list, from, to);
}

回答by Lucas Pires

Simple method

简单的方法

  public static <T> List<T> paginate(Page page, List<T> list) {
      int fromIndex = (page.getNumPage() - 1) * page.getLenght();
      int toIndex = fromIndex + page.getLenght();

      if (toIndex > list.size()) {
        toIndex = list.size();
      }

      if (fromIndex > toIndex) {
        fromIndex = toIndex;
      }

      return list.subList(fromIndex, toIndex);
  }

回答by Averroes

Try this:

试试这个:

int pagesize = 2;
int currentpage = 2;
list.subList(pagesize*(currentpage-1), pagesize*currentpage);

This code returns a list with only the elements you want (a page).

此代码返回一个仅包含您想要的元素的列表(一个页面)。

You should check the index also to avoid java.lang.IndexOutOfBoundsException.

您还应该检查索引以避免 java.lang.IndexOutOfBoundsException。

回答by Amit Deshpande

As per your question simple List.subListwill give you expected behaviour size()/ 2= number of pages

根据您的问题 simpleList.subList会给您预期的行为 size()/ 2= 页数

回答by Reimeus

You could use List.subListusing Math.minto guard against ArrayIndexOutOfBoundsException:

您可以使用List.subListusingMath.min来防范ArrayIndexOutOfBoundsException

List<String> list = Arrays.asList("a", "b", "c", "d", "e");
int pageSize = 2;
for (int i=0; i < list.size(); i += pageSize) {
    System.out.println(list.subList(i, Math.min(list.size(), i + pageSize)));
}