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;
}