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

Time:01-16

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"

CodePudding user response:

try:

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

CodePudding user response:

Not sure if I understand what you want to ask actually because it seems that you already figured it out based on the codes from your question...

So consider that you already has Page<SkcDTO> , and you want to convert it to Page<IQRecordResultDTO> . You first need to have a function to define how to convert one SkcDTO to one IQRecordResultDTO :

public IQRecordResultDTO toIQRecordResultDTO(SkcDTO skc){
    
}

Then you can simply use Page.map() to convert it :

Page<SkcDTO> skcPage = .........
Page<IQRecordResultDTO> result = skcPage.map(skc->toIQRecordResultDTO(skc));
  •  Tags:  
  • Related