我有 2 个数组String key[]
,long value[]
. 键可以重复。我需要唯一键及其映射中值的总和。下面是我正在尝试的代码,但我得到 Array out of bound 异常
public HashMap < String, Long > getValueMap(String key[], long value[]) {
Map newmap = new HashMap();
long count = 0;
for (int i = 0; i < value.length; i++) {
for (int j = 0; j < value.length; j++) {
if (key[i] == key[j]) {
count = count + value[j];
}
}
newmap.put(key[i], count);
count = 0;
}
return (HashMap < String, Long > ) newmap;
}
long[] value = {};
String key[] = {};
int i = 0;
if(!worklogs.isEmpty()){
for(Worklog wl:worklogs){
value[i]=wl.getValue();
key[i]=wl.getAuthor();i++;
}
}
HashMap < String, Long > newhm = getValueMap(key, value);
Iterator entries = newhm.entrySet().iterator();
while (entries.hasNext()) {
Map.Entry entry = (Map.Entry) entries.next();
String newkey = (String) entry.getKey();
Long newvalue = (Long) entry.getValue();
System.out.println("Key = " + newkey + ", Value = " + newvalue);
}
修改了上面的代码,使其看起来简单。请问有人可以帮忙吗?