如何从Collection中返回N个连续的元素?

发布于 2024-10-29 00:20:24 字数 778 浏览 0 评论 0原文

我传递了一个对象集合(在我的例子中是一些 Contact 类),并且需要从该集合返回一个页面。 我的代码感觉比它需要的要长得多。我是否缺少一些库,这些库可以比像下面这样一次迭代每个元素更优雅地执行此操作?

protected Collection<Contact> getPageOfContacts(
  Collection<Contact> contacts, int pageIndex, int pageSize) {
  if (pageIndex < 0 || pageSize <= 0
    || pageSize > contacts.size()) {
    return contacts;
  }
  int firstElement = pageIndex * pageSize;
  int lastElement = (pageIndex + 1) * pageSize - 1;
  Collection<Contact> pagedContacts = new ArrayList<Contact>();
  int index = -1;
  for (Contact contact : contacts) {
    index++;
    if (index < firstElement) {
      continue;
    }
    if (index > lastElement) {
      break;
    }
    pagedContacts.add(contact);
  }
  return pagedContacts;
}

I am passed a collection of objects (some Contact class in my case) and need to return a page from that collection.
My code feels much longer than it needs to be. Am I missing some libraries that could perform that more elegantly than iterating over each element one at a time like I do below?

protected Collection<Contact> getPageOfContacts(
  Collection<Contact> contacts, int pageIndex, int pageSize) {
  if (pageIndex < 0 || pageSize <= 0
    || pageSize > contacts.size()) {
    return contacts;
  }
  int firstElement = pageIndex * pageSize;
  int lastElement = (pageIndex + 1) * pageSize - 1;
  Collection<Contact> pagedContacts = new ArrayList<Contact>();
  int index = -1;
  for (Contact contact : contacts) {
    index++;
    if (index < firstElement) {
      continue;
    }
    if (index > lastElement) {
      break;
    }
    pagedContacts.add(contact);
  }
  return pagedContacts;
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

空‖城人不在 2024-11-05 00:20:24

您可以使用 Guava Iterables.partition

protected <T> Collection<T> getPageOfContacts(
        Collection<T> contacts, int pageIndex, int pageSize) {
    return Lists.newArrayList(
        Iterables.partition(contacts, pageSize)).get(pageIndex);
}

更复杂的版本不会创建所有页面来选择正确的页面,而是在找到正确的页面时停止。

protected <T> Collection<T> getPageOfContacts(
        Collection<T> contacts, int pageIndex, int pageSize) {
    Iterator<List<T>> partitions = Iterators.partition(contacts.iterator(), pageSize);

    for(int page = 0; page<pageSize && partitions.hasNext(); page++){
        List<T> partition = partitions.next();
        if(page == pageIndex) return partition;
    }
    return Collections. <T> emptyList(); //or fail
}

更新:

感谢 ColinD 指出:

Iterables.get(Iterables.partition(contacts, pageSize), pageIndex)

是一个更简单的实现。

You could use Guava Iterables.partition:

protected <T> Collection<T> getPageOfContacts(
        Collection<T> contacts, int pageIndex, int pageSize) {
    return Lists.newArrayList(
        Iterables.partition(contacts, pageSize)).get(pageIndex);
}

A more complex version does not create all pages to pick the right one, but stops when the right page is found.

protected <T> Collection<T> getPageOfContacts(
        Collection<T> contacts, int pageIndex, int pageSize) {
    Iterator<List<T>> partitions = Iterators.partition(contacts.iterator(), pageSize);

    for(int page = 0; page<pageSize && partitions.hasNext(); page++){
        List<T> partition = partitions.next();
        if(page == pageIndex) return partition;
    }
    return Collections. <T> emptyList(); //or fail
}

Update:

Thanks to ColinD to point out that:

Iterables.get(Iterables.partition(contacts, pageSize), pageIndex)

is a simpler implementation.

街道布景 2024-11-05 00:20:24

如果您可以要求将数据分页为 List,则可以使用 Guava

public <T> List<T> getPage(List<T> list, int pageIndex, int pageSize) {
  return Lists.partition(list, pageSize).get(pageIndex);
}

这不涉及复制或迭代(它使用原始列表的子列表视图),并透明地处理少于 pageSize 元素的最终页面。

对于任意 IterableCollection,我会这样做:

public <T> List<T> getPage(Iterable<T> iterable, int pageIndex, int pageSize) {
  return Iterables.get(Iterables.partition(iterable, pageSize), pageIndex);
}

通过提供这两种方法,您将能够处理已知在编译时列出的对象 -尽可能高效地节省时间和任何其他类型的Iterable

If you can require the data to be paged to be a List, you can get a sublist view of a single page easily using Guava:

public <T> List<T> getPage(List<T> list, int pageIndex, int pageSize) {
  return Lists.partition(list, pageSize).get(pageIndex);
}

This involves no copying or iteration (it uses sublist views of the original list) and handles a final page that has fewer than pageSize elements transparently.

For an arbitrary Iterable or Collection, I'd do this:

public <T> List<T> getPage(Iterable<T> iterable, int pageIndex, int pageSize) {
  return Iterables.get(Iterables.partition(iterable, pageSize), pageIndex);
}

By providing both these methods, you'd be able to handle objects that are known to be lists at compile-time efficiently and any other type of Iterable as efficiently as you can.

做个少女永远怀春 2024-11-05 00:20:24

如果您希望元素有明确的顺序,则应该使用List,而不是collectionListCollection 之间的基本区别在于 List 的元素有固定的顺序。它还定义了非常方便的方法 subList(int start, int end),它创建一个子列表,它是原始列表的别名,仅包含您想要的元素,而无需将它们复制到新列表。

If you want a defined order to your elements, you should be using a List, not a collection. The basic difference between List and Collection is that List has a fixed order to the elements. It also defines the very convenient method subList(int start, int end) which creates a sub-list which is an alias of the original list containing just the elements you want without the overhead of copying them to a new list.

动听の歌 2024-11-05 00:20:24

List 接口提供了一个 subList 方法,该方法采用起始索引和结束索引。请参阅 http://download .oracle.com/javase/6/docs/api/java/util/List.html#subList(int,%20int)。返回的子列表由原始列表支持,因此您可能想要执行某些操作喜欢

protected Collection<Contact> getPageOfContacts(...) {
    return new ArrayList<Contact>(original.subList(start,end));
}

The List interface provides a subList method, that takes a start index and an end index. See http://download.oracle.com/javase/6/docs/api/java/util/List.html#subList(int,%20int). The returned sublist is backed by the original list, so you probably want to do something like

protected Collection<Contact> getPageOfContacts(...) {
    return new ArrayList<Contact>(original.subList(start,end));
}
薄情伤 2024-11-05 00:20:24
return new ArrayList<Contact>(new ArrayList<Contact>(contacts).subList(firstElement, lastElement));

注意:这将返回子列表 exclusive lastElement

注意 2:由于 Kevin 提到的原因,结果被复制到另一个列表。

return new ArrayList<Contact>(new ArrayList<Contact>(contacts).subList(firstElement, lastElement));

Note: this will return the sublist exclusive lastElement

Note 2: The result are copied to another list for the reasons mentioned by Kevin.

忘羡 2024-11-05 00:20:24
Iterables.partition(contacts, pageSize).forEachRemaining(paginatedContacts->{/*Operation here*/});
Iterables.partition(contacts, pageSize).forEachRemaining(paginatedContacts->{/*Operation here*/});
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文