findAll(Pageable) returns wrong sorting order

290 views Asked by At

Why PagingAndSortingRepository<City, Long> return wrong sorting order after method findAll(Pageable)? In service layer I have this method and I'm trying to sort by population:

    public Set<City> findAllPageable(int page, int size, String sortBy) {
        Pageable paging = PageRequest.of(page, size, Sort.by(sortBy));
        return new HashSet<>(repository.findAll(paging).getContent());
    }

This is what I expected to see:

    select Population from city order by Population limit 10;
42
167
300
455
503
559
595
682
700
800

And this is the actual result after iterating the Set<City>:

682, 42, 300, 700, 559, 595, 800, 167, 455, 503

All these numbers are correct but the order is incorrect. Why?

2

There are 2 answers

0
Mureinik On BEST ANSWER

You can't rely on the order elements are returned in a HashSet. If you must use a set there, use a LinkedHashSet, which guarantees the order:

return new LinkedHashSet<>(repository.findAll(paging).getContent());
0
Nikolas Charalambidis On

The returned HashSet implementation doesn't maintain the sorting order of the cities.

Use the TreeSet implementation and pass either a Comparator<City> or let City implement Copmarable<City>. I also suggest you to return SortedSet<City> in that case.

The elements are ordered using their natural ordering, or by a Comparator provided at set creation time, depending on which constructor is used.

public SortedSet<City> findAllPageable(int page, int size, String sortBy) {
     Pageable paging = PageRequest.of(page, size, Sort.by(sortBy));
     return new TreeSet<>(
         repository.findAll(paging).getContent(), 
         Comparator.comparing(City::getPopulation));
}