Search code examples
sortingpaginationspring-datavaadin8

Paging and sorting over Collection


I want to apply paging and sorting to ArrayList of photos. The list is retrived by rest client. Here is my attempt to paging but returns all 5k elements instead. I try to achive a paging like in JpaRepository. The sorting is done by compareTo() method, and doesn't seem to work properly either.

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 implements 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;
    }
}

Solution

  • Getting all photos and the wrapping that in a PageRequest instance with the page size and sorting set will not do what you want. The PageRequest class (or PageImpl class) does not perform the slicing of a list of data into a page or perform the sorting. You must do that yourself

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