'How to convert ArrayList to Pageable object springboot
I was trying to return list as page object to my client side angular Application. But it return all the list not a page.
this is my server side controller method which return the list
@GetMapping("/users/departmentAdminPageUsers")
@Timed
public ResponseEntity<List<DepartmentAdminPageUserDTO>> getDepartmentAdminPageUsers(@ApiParam Pageable pageable, @ApiParam String searchKey, @ApiParam String depId)
throws URISyntaxException {
List<DepartmentAdminPageUserDTO> userList=userService.getAllDepartmentAdminPageUsers(depId,searchKey);
final Page<DepartmentAdminPageUserDTO> page = new PageImpl<>(userList, pageable,userList.size());
HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/users/departmentAdminPageUsers");
return new ResponseEntity<>(page.getContent(), headers, HttpStatus.OK);
}
this is my client side angular method which send request
getAllUsersByDepId(req?: any):Observable<Response>{
let params: URLSearchParams = new URLSearchParams();
if (req) {
params.set('page', req.page);
params.set('size', req.size);
params.set('searchKey', req.searchKey);
params.set('depId', req.depId);
}
let options = {
search: params
};
return this.http.get(this.resourceUrl+ '/departmentAdminPageUsers', options);
}
I need to return page instead the whole list.
Solution 1:[1]
you are returning the whole list as the page content, try:
List<DepartmentAdminPageUserDTO> userSubList = userList.subList((pageable.getPage()-1)*pageable.getSize(), (pageable.getPage()*pageable.getSize())-1);
final Page<DepartmentAdminPageUserDTO> page = new PageImpl<>(userSubList, pageable,userList.size());
Solution 2:[2]
protected Page<T> listToPage(Pageable pageable, List<T> entities) {
int lowerBound = pageable.getPageNumber() * pageable.getPageSize();
int upperBound = Math.min(lowerBound + pageable.getPageSize() - 1, entities.size());
List<T> subList = entities.subList(lowerBound, upperBound);
return new PageImpl<T>(subList, pageable, subList.size());
};
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | snukluck |