Map存储两个key:Duplicate key 6

简介: Map存储两个key:Duplicate key 6

map中的key是唯一的,如果map存储出现重复的key就会报错,所以key一般要选择唯一索引的字段

解决方案

 Map<String, Integer> sumTimeMap =
            workTimeVoList.stream().collect(Collectors.toMap(WorkTimeVo::getUserAccount, WorkTimeVo::getSumUseTime);

改为

 Map<String, Integer> sumTimeMap =
            workTimeVoList.stream().collect(Collectors.toMap(WorkTimeVo::getUserAccount, WorkTimeVo::getSumUseTime, (entity1, entity2) -> entity1));
            

出现重复时,存放最后一次的value,此处可以根据需求自行处理;

思考

map的key不可以重复,value可以,那么同一个key可以存储两个值吗,事实上是可以的

IdentityHashMap类利用哈希表实现 Map 接口,比较键(和值)时使用引用相等性代替对象相等性

package test;

import java.util.IdentityHashMap;

import java.util.Map;

import java.util.Map.Entry;

public class test1 {
public static void main(String[] args) {
String str1 = new String("xx");

String str2 = new String("xx");

System.out.println(str1 == str2);

Map map = new IdentityHashMap();

map.put(str1, "hello");

map.put(str2, "world");

for(Entry entry : map.entrySet())

{
System.out.println(entry.getKey()+" " + entry.getValue());

}

System.out.println(" containsKey---> " + map.containsKey("xx"));

System.out.println("str1 containsKey---> " + map.containsKey(str1));

System.out.println("str2 containsKey---> " + map.containsKey(str2));

System.out.println(" value----> " + map.get("xx"));

System.out.println("str1 value----> " + map.get(str1));

System.out.println("str2 value----> " + map.get(str2));

}

}

我们的看看输出的结果为:

false

xx world

xx hello

containsKey—> false

str1 containsKey—> true

str2 containsKey—> true

value----> null

str1 value----> hello

str2 value----> world

而将

String str1 = new String(“xx”);

String str2 = new String(“xx”);

替换为

String str1 = “xx”;

String str2 = “xx”;

则不会填入两个value

原因就是因为String是常量,同样的xx如果不new一块新的内存,它就会使用之前的引用

目录
相关文章
|
20天前
|
JavaScript 索引
v-for中key左右
v-for中key左右
8 1
|
1月前
|
数据库 Python
Duplicate entry for key username
Duplicate entry for key username
21 0
|
8月前
|
关系型数据库 MySQL 数据库
解决出现的SQLIntegrityConstraintViolationExceptionw:Duplicate entry ‘10‘ for for key ‘user.PRIMARY‘问题
解决出现的SQLIntegrityConstraintViolationExceptionw:Duplicate entry ‘10‘ for for key ‘user.PRIMARY‘问题
|
算法 JavaScript 前端开发
|
数据库
查看key
查看key
105 0