4

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.

C. Weber
  • 907
  • 5
  • 18
drizzt.dourden
  • 683
  • 8
  • 20

2 Answers2

1

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().

Stuck
  • 11,225
  • 11
  • 59
  • 104
0

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 
}
Community
  • 1
  • 1
J-Alex
  • 6,881
  • 10
  • 46
  • 64
  • I believe that doesn´t answers the OPs question. He is looking for a more elegant solution to iterate over the pages not the content of one page. – C. Weber Jan 10 '19 at 16:30
  • I know I can use the getContent() , but the problem is the list will eat my memory with all data. I want to process Pages of data. – drizzt.dourden Jan 10 '19 at 17:13