Custom Pagination from a Java List of Objects using Spring Data JPA

Sonu Singh
1 min readDec 9, 2022

--

Pagination is often helpful when we have a large dataset and we want to present it to the user in smaller chunks.

Also, we often need to sort that data by some criteria while paging.

In this tutorial, we’ll learn how to easily create custom pagination using Spring Data JPA.

Below is the sample Rest API code with custom pagination from a list of objects.

@RequestMapping(value = "/tickets", method = { RequestMethod.GET }, produces = { "application/json" })
@ResponseBody
public Page<Ticket> ticketListWithPagination(@RequestParam(value = "page", defaultValue = "0", required = true) int page,
@RequestParam(value = "size", defaultValue = "1", required = true) int size) {

final Page<Ticket> tickets;
Pageable pageable = new PageRequest(page, size);
List<Tickte> listofTicktes = ticketRepo.findAll();

final int start = (int) pageable.getOffset();
final int end = Math.min((start + pageable.getPageSize()), listofTicktes.size());

if (CollectionUtils.isNotEmpty(listofTicktes)) {
ticketsPage = new PageImpl<>(listofTicktes.subList(start, end), pageable, listofTicktes.size());
} else {
ticketsPage = new PageImpl<>(listofTicktes, pageable, 0);
}
return ticketsPage;
}

Thank you for reading this article.

Happy Learning.

--

--

Sonu Singh
Sonu Singh

Responses (2)