记:stream流中toMap()使用

Map<Integer, String> map = list.stream().collect(Collectors.toMap(Person::getId, Person::getName,(oldValue, newValue) -> newValue));

toMap()最少接收两个参数
这个方法碰到重复的key会抛出异常,把张三和李四的id改成一样,再次运行机会抛出异常
所以使用这个方法时需要注意,这时可以通过第三个参数来解决重复key的问题

Map<Integer, ProductCategoryResultDTO> resultDTOMap = byCategoryFidAndEnvironmentTag.stream()
                    .collect(Collectors.toMap(ProductCategory::getCategoryId, v -> {
                        ProductCategoryResultDTO productCategoryResultDTO = new ProductCategoryResultDTO();
productCategoryResultDTO.setStatus(v.getUplowState());
                        return productCategoryResultDTO;
                    }, (key1, key2) -> key2));

此时key2的值可以覆盖key1

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
streamtoMap()方法一般需要至少两个参数。第一个参数是用于指定键值对键的选择器,第二个参数是用于指定值的选择器。例如,可以使用类的方法引用作为选择器,例如Person::getId或Student::getClass。 当遇到重复的键时,toMap()方法会抛出异常。为了解决这个问题,可以添加第三个参数作为合并函数来处理重复的键。合并函数定义了当遇到重复键时,如何选择值。合并函数的参数类型应与值的类型相匹配。一个常见的合并函数是使用BigDecimal类的add()方法来对值进行求和。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *3* [streamtoMap()使用](https://blog.csdn.net/Airuiliya520/article/details/125426147)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] - *2* [streamtoMap](https://blog.csdn.net/qq_29362451/article/details/121034282)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值