对 Collection 进行分页和排序

Paging and sorting over Collection

我想对照片的 ArrayList 应用分页和排序。该列表由其余客户端检索。这是我尝试分页但 returns 所有 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 class(或 PageImpl class)不执行将数据列表切片到页面中或执行排序。你必须自己做

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());