Search code examples
javaarraysspringspring-data

How to create Page<> object by using another Page on Java?


I am using jpa paging and getting Page object but I want to return another type of Page object to front end after making some operations on SkcDto. I already have operations which creates IQRecordResultDTO array from the SkcDto

private IQRecordResultDTO[] generateIQRecords(List<SkcDTO> iqList) {

//Some operations

return iQRecordResultDTO[];
}

And here is the code which calls the above conversion code:

public Page<SkcDTO> generateIQRecordsPage(Query query, Pageable pageable) {
    Page<SkcDTO> skcDTOPage = skcService.iqRecordsByCriteriaAsPage(query, pageable);

    List<SkcDTO> skcList = skcDTOPage.getContent();

    IQRecordResultDTO[] resultArray = generateIQRecords(skcList);

    //HERE IS WHAT I WANT AND NEED TO BE CHANGE I THINK. OR JUST SET NEW CONTENT[] AND ALL OTHER STUFF WILL BE SAME LIKE PAGENUMBER, TOTAL ELEMENT ETC.
    Page<IQRecordResultDTO> iqResultPage = skcDTOPage.map(skc -> {
        IQRecordResultDTO resultDto = convertSkcToIQResultDTO(skc);
        return resultDto;
    });

    return skcDTOPage;
}

I already have Page succesfully but if I apply pagination to this page then I do pagination on another page and result is becoming wrong. So I just want to return correct type of Page object, everything will be same (page number, totalPage, totalElement etc) but the content[] of the object will be set to another type.

I could not find something like "just copy the Page including all elements except content[] of it"


Solution

  • try:

    Page<IQRecordResultDTO> iqResultPage = new PageImpl<IQRecordResultDTO>(
                    Arrays.asList(generateIQRecords(skcDTOPage.getContent())), 
                    skcDTOPage.getPageable(),
                    skcDTOPage.getTotalElements()
    );