Conversion of List to Page in Spring

Solution 1:

I had the same problem. I used subList:

final int start = (int)pageable.getOffset();
final int end = Math.min((start + pageable.getPageSize()), users.size());
final Page<User> page = new PageImpl<>(users.subList(start, end), pageable, users.size());

Solution 2:

There is a Page implementation for that:

Page<Something> page = new PageImpl<>(yourList);

Solution 3:

As indicated in the reference documentation, Spring Data repositories support pagination on query methods by simply declaring a parameter of type Pageable to make sure they're only reading the data necessary for the requested Page.

Page<User> page = findAllByProgramId(Integer programId, Pageable pageable);

That would return a Page object with the page size/settings defined in your Pageable object. No need to get a list and then try to create a page out of it.

Solution 4:

You should do it like advised by the dubonzi's answer.

If you still want to use pagination for a given List use PagedListHolder:

List<String> list = // ...

// Creation
PagedListHolder page = new PagedListHolder(list);
page.setPageSize(10); // number of items per page
page.setPage(0);      // set to first page

// Retrieval
page.getPageCount(); // number of pages 
page.getPageList();  // a List which represents the current page

If you need sorting, use another PagedListHolder constructor with a MutableSortDefinition.

Solution 5:

Try This:

public Page<Patient> searchPatientPage(SearchPatientDto patient, int page, int size){
        List<Patient> patientsList = new ArrayList<Patient>();
        Set<Patient> list=searchPatient(patient);
        patientsList.addAll(list);
        int start =  new PageRequest(page, size).getOffset();
        int end = (start + new PageRequest(page, size).getPageSize()) > patientsList.size() ? patientsList.size() : (start + new PageRequest(page, size).getPageSize());

        return new PageImpl<Patient>(patientsList.subList(start, end), new PageRequest(page, size), patientsList.size());
    }