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?
You can't rely on the order elements are returned in a
HashSet
. If you must use a set there, use aLinkedHashSet
, which guarantees the order: