解决java.lang.IllegalStateException: Duplicate key异常

项目重启后突然报这个异常

在这里插入图片描述

看日志应该是在初始化字典,源代码

private Map dictMap;

 @PostConstruct
 publicvoid init() {
     List eventType = DictUtils.getDictCache("xxx");
     dictMap = eventType.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
 }

这里的操作是把词典list转换成map,然后key冲突。

但我比对了一下数据,没有找到重复的dictValue,报这个错有点莫名其妙。

最后的解决办法参考了其他网友,得以顺利解决,最后上修改后的代码

private Map dictMap;

@PostConstruct
public void init() {
    if (dictMap == null || dictMap.isEmpty()) {
        List eventType = DictUtils.getDictCache("xxx");
        dictMap = eventType.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel, (entity1, entity2) -> entity1));
    }
}

Collectors.toMap增加了第三个参数(entity1, entity2) -> entity1),这个参数的意思是如果entity1、entity2的key值相同,选择entity1作为那个key所对应的value值。

参考:https://blog.csdn.net/weixin_40873693/article/details/124659750

本文来自网络,不代表协通编程立场,如若转载,请注明出处:https://net2asp.com/fb8b780924.html