英文:
findAll(Pageable) returns wrong sorting order
问题
为什么PagingAndSortingRepository<City, Long>在调用方法findAll(Pageable)之后返回错误的排序顺序?
在服务层中,我有以下方法,我想通过人口来进行排序:
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());
}
这是我期望看到的结果:
select Population from city order by Population limit 10;
42
167
300
455
503
559
595
682
700
800
而在迭代Set<City>之后,实际结果如下:
682, 42, 300, 700, 559, 595, 800, 167, 455, 503
所有这些数字都是正确的,但顺序是错误的。为什么呢?
英文:
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?
答案1
得分: 2
你不能依赖于在 HashSet 中返回元素的顺序。如果你必须在这里使用一个集合,可以使用 LinkedHashSet,它保证了顺序:
return new LinkedHashSet<>(repository.findAll(paging).getContent());
英文:
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());
答案2
得分: 1
返回的 HashSet 实现不会保持城市的排序顺序。
请使用 TreeSet 实现,并传递一个 Comparator<City>,或让 City 实现 Comparable<City>。我还建议在这种情况下返回 SortedSet<City>。
这些元素根据它们的自然顺序排序,或者根据在集合创建时提供的比较器进行排序,具体取决于使用哪个构造函数。
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));
}
英文:
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));
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论