Pageable pageable = PageRequest.of(1, 3, Sort.by("name").ascending()); Page<User> page = userRepository.findAll(pageable); List<User> users = page.getContent(); return users.stream().map(User::getName).toList();
The Pageable requests page 1 (second page) with 3 items per page, sorted by name ascending. So the first page (index 0) has the first 3 names alphabetically, the second page has the next 3.
PageRequest.of is the correct factory method. Sort.by("age").descending() creates the descending sort.
Pageable pageable = PageRequest.of(0, 5); Page<Item> page = itemRepository.findAll(pageable); int totalPages = page.getTotalPages();
23 items with 5 per page means 4 pages fully filled (5*4=20) plus 1 page with 3 items, total 5 pages. 23/5 = 4.6, rounded up is 5 pages.
Pageable pageable = PageRequest.of(-1, 10); Page<Product> page = productRepository.findAll(pageable);
PageRequest.of requires a non-negative page index. Negative page index causes IllegalArgumentException.
Spring Data applies sorting in the order the Sort.Order objects are given. The first order is primary, the second is secondary.
