使用場景:
在實際應用開發中,會常把一個List的查詢數據集合轉爲一個Map,那麼在這裏的 list.stream().collect()其實就是做了這麼一件事情,它是java8的stream方式實現的它是以type爲key,以entity對象爲value構成Map。
//查詢
List<QuestionCategoryEntity> list = questionCategoryService.selectList(entityWrapper);
Map<String, String> categoryMap = list.stream().collect(
Collectors.toMap(
QuestionCategoryEntity::getCategoryCode,
QuestionCategoryEntity::getCategoryName
)
);
在有些業務場景中會出現如下異常:Duplicate key ,map的key重複,如上的 QuestionCategoryEntity::getCategoryCode。
java.lang.IllegalStateException: Duplicate key 專項考試
at java.util.stream.Collectors.lambda$throwingMerger$0(Collectors.java:133)
at java.util.HashMap.merge(HashMap.java:1245)
at java.util.stream.Collectors.lambda$toMap$58(Collectors.java:1320)
at java.util.stream.ReduceOps$3ReducingSink.accept(ReduceOps.java:169)
at java.util.ArrayList$ArrayListSpliterator.forEachRemaining(ArrayList.java:1374)
... ...
解決方法:
使用toMap()的重載方法,如果已經存在則不再修改,直接使用上一個數據。
//查詢
List<QuestionCategoryEntity> list = questionCategoryService.selectList(entityWrapper);
Map<String, String> categoryMap = list.stream().collect(
Collectors.toMap(
QuestionCategoryEntity::getCategoryCode,
QuestionCategoryEntity::getCategoryName,
(entity1, entity2) -> entity1
)
);
等效於
questionCategoryService.selectList(entityWrapper);
Map<String, String> categoryMap = list.stream().collect(
Collectors.toMap(
QuestionCategoryEntity::getCategoryCode,
QuestionCategoryEntity::getCategoryName,
(entity1, entity2) {
return entity1
}
)
);
(entity1, entity2) -> entity1 這裏使用的箭頭函數,也就是說當出現了重複key的數據時,會回調這個方法,可以在這個方法裏處理重複Key數據問題,小編這裏粗暴點,直接使用了上一個數據。