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{
publicstaticvoidmain(String[] args){
String str1= newString("xx");
String str2= newString("xx");
System.out.println(str1== str2);
Map map= newIdentityHashMap();
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一块新的内存,它就会使用之前的引用