Java8 Collectors.toMap的key重复

时间:2022-07-26
本文章向大家介绍Java8 Collectors.toMap的key重复,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

**

Map<String, BottomAccount> map = bottomAccountList.stream().collect(Collectors.toMap(BottomAccount::getGoodName, Function.identity()));

如这个地方,如果使用GoodName为map的key,货物名称有可能会重复,这时候就会报Duplicate Key的问题,其实是map的key重复了,首先查看源码:

显而易见,throwingMerger()是一个出现异常时默认执行的方法,可以看到,入参是HashMap,大胆猜测、小心求证,我们猜最终是由HashMap去执行的Merger方法,

看HashMap里的一段代码:

这就能证明当出现map的key重复时会报错Duplicate Key的异常了。

如果不想抛异常,自己给传一个新的key值用于替换原有值。

所以,

解决方案一 :给重复的Key设置一个新的值

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

但是考虑到实际业务中,给重复的key设置一个新的值并不符合需求,所以,

解决方案二:使用其他字段为map的key,如主键id

Map<String, BottomAccount> map = bottomAccountList.stream().collect(Collectors.toMap(BottomAccount::getId, Function.identity()));

原来的map中的key就变成了value

map.values().stream().map(BottomAccount::getGoodName).collect(Collectors.toList())