Walk all results using a Spring Data and pagination

Viewed 918

I'm calling a paginate service I can walk all the paginated collection using code like this:

Pageable pageable = PageRequest.of(0,100);
Page<Event> events = eventsService.getEventsPage(pageable);
while(!events.isLast()) {
    doStuff(events)
    events = eventsService.getEventsPage(events.nextPageable())
}
doStuff(events) // rest of events

is there a more elegant solution?. I need the pagination because otherwise, the system will run out of memory.

2 Answers

I'd use the getContent() from Slice (which is inherited by Page).

List <T> getContent()

Returns the page content as List.

Pageable pageable = PageRequest.of(0,100);
Page<Event> events = eventsService.getEventsPage(pageable);
List<Event> eventList = events.getContent();
for (Event event : eventList) {
    // do stuff 
}

I feel like having to state the service call and doStuff twice is somehow fragile. You can utilze the fact that nextPageable() will give you the unpaged singleton if the current page is the last one already.

Pageable pageable = PageRequest.of(0,100);
do {
    Page<Event> events = eventsService.getEventsPage(pageable);
    doStuff(events)
    pageable = events.nextPageable();
} while(pageable.isPaged())

Here is the doc of nextPageable().

 /**
 * Returns the {@link Pageable} to request the next {@link Slice}. Can be {@link Pageable#unpaged()} in case the
 * current {@link Slice} is already the last one. Clients should check {@link #hasNext()} before calling this method.
 *
 * @return
 * @see #nextOrLastPageable()
 */
Pageable nextPageable();

Pageable#unpaged() will return a singleton that returns false for isPaged().

Related