我想对照片的ArrayList应用分页和排序。该列表由其余客户端检索。这是我尝试分页,但返回所有 5k 元素。我尝试实现像 JpaRepository 中那样的分页。排序是通过compareTo()方法完成的,似乎也不能正常工作。
PhotoServiceImpl.java
private List<Photo> repository;
public PhotoServiceImpl() {
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<List<Photo>> photoResponse = restTemplate.exchange("https://jsonplaceholder.typicode.com/photos", HttpMethod.GET, null, new ParameterizedTypeReference<List<Photo>>() {
});
this.repository = photoResponse.getBody();
}
@Override
public List<Photo> findAll() {
return repository;
}
@Override
public Page<Photo> findAll(Pageable pageable) {
List<Photo> photos = findAll();
return new PageImpl<Photo>(photos, new PageRequest(pageable.getPageNumber(), pageable.getPageSize()), photos.size());
}
@Override
public Page<Photo> findAll(Pageable pageable, Sort.Direction sortOrder) {
List<Photo> photos = findAll();
return new PageImpl<Photo>(photos, new
PageRequest(pageable.getPageNumber(), pageable.getPageSize(), sortOrder), photos.size());
}
@Override
public List<Photo> findAll(Sort.Direction sortOrder) {
List<Photo> photos = repository
.stream()
.sorted()
.collect(Collectors.toList());
if (sortOrder.isDescending())
Collections.reverse(photos);
return photos;
}
Photo.java 实现 Comparable
private int id;
private int albumId;
private String title;
private URL url;
private URL thumbnailUrl;
@Override
public int compareTo(Object o) {
Photo out = ((Photo) o);
int c;
c = Integer.compare(this.getId(), out.getId());
if (c == 0)
c = Integer.compare(this.getAlbumId(), out.getAlbumId());
if (c == 0)
c = this.getTitle().compareTo((out.getTitle()));
return c;
}
}
在具有页面大小和排序设置的
PageRequest
实例中获取所有照片和包装不会达到您想要的效果。 PageRequest
类(或PageImpl类)不执行将数据列表切片到页面中或执行排序。你必须自己做
List<Photo> photos = findAll();
//
// << Add your page extraction and sorting code here >>
//
return new PageImpl<Photo>(photos,
new PageRequest(pageable.getPageNumber(), pageable.getPageSize(), sortOrder), photos.size());