【问题标题】:Can we sort List<T> from Spring boot Pageable or sort page from PageImpl?我们可以从 Spring Boot Pageable 中对 List<T> 进行排序,还是从 PageImpl 中对页面进行排序?
【发布时间】:2019-11-18 16:21:43
【问题描述】:

我有在 Spring Boot 中将 List 转换为 Page 的业务逻辑。

在该代码中,我的可分页排序不在输出中排序。

如果我可以通过 pageable 排序或从 pageable.getSort() 排序 List,有没有办法?

  • 注意:我正在使用 new PageImpl() 将 List 转换为 Page。*

    int start = (int) pageable.getOffset(); int end = (start + pageable.getPageSize()) > List.size() ? List.size() : (start + pageable.getPageSize()); Page paginatedList = new PageImpl(floorsheetList.subList(start, end), pageable, list.size());

我实际上得到了 sorted=true 但数据不会排序。

sort: {
sorted: true,
unsorted: false,
empty: false
}

更新

Turns out PageImpl cannot sort the data. So have to manually sort it via Collections or any other APIs.

【问题讨论】:

  • Spring Data 直接支持 Page,因此如果您使用 Spring 数据从数据库中检索对象列表,您可以重构该代码以直接返回 Page,即将被排序。

标签: java spring-boot sorting java-8 pagination


【解决方案1】:

原来 PageImpl 无法对数据进行排序。因此必须通过 Collections 或任何其他 API 手动对其进行排序。

【讨论】:

    【解决方案2】:

    你使用 pageImpl 就像你在新页面中设置变量一样,所以页面中的内容不是排序的。

    你得到 sorted = true 因为你在 pageable 中设置了排序。

    如果要对页面中的内容进行排序,则应在设置 PageImpl 之前使用 Collections.sort 对 List 内容进行排序。

    【讨论】:

    • 谢谢。我错过了有关 PageImpl 无法进行排序部分的文档。这是我的错误。 :)
    猜你喜欢
    • 2021-12-25
    • 1970-01-01
    • 1970-01-01
    • 2019-12-13
    • 1970-01-01
    • 1970-01-01
    • 2020-11-18
    • 2011-06-11
    相关资源
    最近更新 更多