【发布时间】:2011-07-27 19:42:58
【问题描述】:
我传递了一个对象集合(在我的例子中是某个 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;
}
【问题讨论】:
-
收藏是如何消费的?你用什么方法/打算用什么方法?
标签: java collections iteration paging guava