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一块新的内存,它就会使用之前的引用

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

渐暖°

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值