1

Is there a Spring utility that allows to create a Page instance starting from a Java Collection?

Something like:

Page<MyObject> myObjPage = PagingUtils.createPageFromCollection(listOfMyObjects, pageable);

Or should I manually implement paging and sorting logic manually?

davioooh
  • 23,742
  • 39
  • 159
  • 250
  • A `Page` is just a holder for data it doesn't do paging and sorting. That is left to the repository to implement. Why do you want to turn a collection into a page in the first place? – M. Deinum Jul 12 '21 at 14:32
  • @M.Deinum in my project the collection acts as a "table" so, I need to retrieve a page of what is contained in this collection. – davioooh Jul 12 '21 at 15:04
  • Then you need to write a repository that handles your collection as a table and does sorting/paging on that. – M. Deinum Jul 12 '21 at 16:42

3 Answers3

1

I think your question can be answered with this link.

Answer seems u need to implement manually.

Cerakoted
  • 19
  • 4
1

Consider 2 scenarios-

  1. I want data from spring as paging and sorting then
    i) Create a sort object of (org.springframework.data.domain.Sort)
Sort sort = sortType.equals("ASC") ? Sort.by(sortField).ascending() :
                Sort.by(sortField).descending();

ii) Pass this sort type to a pageable object

Pageable pageable = PageRequest.of(pageId, pageSize, sort);

iii) Pass this pageable object to JPArepository method

yourRepository.findAll(pageable);

This will return data with pagination and sorting.

Case 2 - Your scenario - From a collection object I want data with pagination

then you have to take the help from PageImpl class. which offer 2 Constructor to do this

PageImpl(List<T> content, Pageable pageable, long total)

where

  1. content – the content of this page(Your collection object).
  2. pageable – the paging information
  3. total – the total amount of items available.

There is also another constructor

PageImpl(List<T> content)

Note - This will result in the created Page being identical to the entire List.

Ayush
  • 349
  • 1
  • 7
0

Pageable pageable = PageRequest.of(pageNo-1, pageSize);

Page page = questionRepository.findAll(pageable);

List question = page.getContent();

tushar
  • 69
  • 5