Skip to content

core-java-samples/pagination-sorting-sample

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

5 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

pagination-sorting-sample

Extends pagination-pageable-sample with sorting support.

What It Demonstrates

Adds a Comparator<T> to the Pageable request.

Before slicing the dataset into pages, the repository sorts the full list by the comparator provided — so the order of records is consistent across all pages.

Passing null skips sorting.

Structure

All code is in a single file: PaginationSorting.java

PaginationSorting.java
│
├── Owner                   # Entity — record with id and name
├── Page<T>                 # Pagination result — content + metadata (page, size, total)
├── Pageable<T>             # Pagination request — page, size and Comparator<T>
├── FakeOwnerRepository     # In-memory implementation — sorts then paginates
└── PaginationSorting       # Entry point + demo()

Key Points

Comparator is part of the request. Pageable<T> carries a Comparator<T> alongside page number and size — the sort order travels with the pagination parameters.

Sorting happens before pagination. The full dataset is sorted first, then sliced — this ensures consistent ordering across all pages.

Original data is never mutated. The repository copies the source list before sorting — the underlying LinkedHashMap stays unchanged.

Null means no sorting. Passing null as comparator returns records in insertion order.

Console Output

Page[content=[Owner[id=5, name=jack5], Owner[id=4, name=jack4]], page=0, size=2, total=5]

Page[content=[Owner[id=1, name=jack1], Owner[id=2, name=jack2]], page=0, size=2, total=5]

First result — sorted by id descending. Second result — no sorting, insertion order.

Run

./mvnw spring-boot:run

See also

About

Offset-based pagination with sorting in pure Java.

Topics

Resources

Stars

Watchers

Forks

Contributors

Languages