Collectors.toMap 多个字段为key
时间: 2023-10-15 16:26:12 浏览: 315
要使用Collectors.toMap函数将多个字段作为key,你可以通过创建一个自定义的key提取器(KeyExtractor)来实现。在提取器中,你可以将多个字段组合成一个唯一的key,以确保不会出现重复的key值。以下是一个示例代码:
```
Map<String, Person> personMap = personList.stream()
.collect(Collectors.toMap(p -> p.getFirstName() + "_" + p.getLastName(), Function.identity()));
```
在这个示例中,我们将一个Person对象的firstName和lastName字段组合成一个唯一的key。如果存在两个Person对象具有相同的firstName和lastName,那么它们将被视为重复的key,并且会引发IllegalStateException异常。为了解决重复key的问题,你可以使用第三个参数来定义解决冲突的策略,例如选择保留旧值或者选择保留新值。<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* [ListToMapDuplicateKey.java](https://download.csdn.net/download/snxkxk/12321923)[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_2"}}] [.reference_item style="max-width: 33.333333333333336%"]
- *2* [Stream流Collectors.toMap用法](https://blog.csdn.net/m0_55070913/article/details/126516665)[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_2"}}] [.reference_item style="max-width: 33.333333333333336%"]
- *3* [Java 8 lamda Stream的Collectors.toMap 参数](https://blog.csdn.net/qq_43842093/article/details/125031924)[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_2"}}] [.reference_item style="max-width: 33.333333333333336%"]
[ .reference_list ]
阅读全文