Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java stream usage for achieving pagination

I am returning a list of transactions as like below;

List<AccountTransactions> products = accountTransactionRepository.findAll(specification);
    
// Currently all record are returned
List<AccountTransactionDto> transactionDtos = AccountTransactionMapper.toAccountTransactionDtoList(products) 
 .stream().collect(Collectors.toList());

I want to return record with pagination.
Suppose the list of transactions has 22 records.

Example 1:

PageSize=2 Page=10
1 2 | 3 4 | 5 6 | 7 8 | 9 10 | 11 12 | 13 14 | 15 16 | 17 18 | 19 20 | 21 22

Return a list containing transaction 19 and 20.

Example 2:

PageSize=5 Page=5
1 2 3 4 5 | 6 7 8 9 10 | 11 12 13 14 15 | 16 17 18 19 20 | 21 22

Return a list containing transaction 21 and 22.

How could I do this by using Stream API?


1 Answers

  int pageSize = 5;
  int page = 5;

  List<AccountTransactionDto> transactionDtos = AccountTransactionMapper.toAccountTransactionDtoList(products)
                .stream()
                .skip((page - 1) * pageSize)
                .limit(pageSize)
                .collect(Collectors.toList());
like image 54
divilipir Avatar answered Apr 25 '26 07:04

divilipir



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!