繁体   English   中英

Java stream 用于实现分页

[英]Java stream usage for achieving pagination

我正在返回如下交易列表;

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

我想用分页返回记录。
假设交易列表有 22 条记录。

示例 1:

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

返回包含事务 19 和 20 的列表。

示例 2:

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

返回包含事务 21 和 22 的列表。

我怎么能通过使用 Stream API 来做到这一点?

  int pageSize = 5;
  int page = 5;

  List<AccountTransactionDto> transactionDtos = AccountTransactionMapper.toAccountTransactionDtoList(products)
                .stream()
                .skip((page - 1) * pageSize)
                .limit(pageSize)
                .collect(Collectors.toList());

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM