public class MyHashMapextends HashMap>{
@Override
public HashMapput(K key, HashMap value){
if (containsKey(key)){
Set vkset = value.keySet();
Set mpkeyset = get(key).keySet();
HashMap map = get(key);
for (String str : vkset){
if (mpkeyset.contains(str)){
map.put(str, value.get(str) + get(key).get(str));
} else {
map.put(str, value.get(str));
}
}
return super.put(key, map);
}
return super.put(key, value);
}
}
重写put方法,这个方法的优势就是做统计,一共涉及到三个字段,A B C 输入的数据是N个ABC 现在的需求就是按照A为唯一值统计B字段的值的的结果C进行统计(确实不好说明白直接上demo)
MyHashMap myHashMap =new MyHashMap();
for (int i =0; i <100000; i++){ // TODO,十万次数据测试
HashMap hashMap =new HashMap();
hashMap.put("001", 1.00);
hashMap.put("002", 2.00);
myHashMap.put("11", hashMap);
}
for (int i =0; i <100000; i++){ // TODO,十万次数据测试
HashMap hashMap =new HashMap();
hashMap.put("001", 1.00);
hashMap.put("002", 2.00);
myHashMap.put("111", hashMap);
}
for (int i =0; i <100000; i++){ // TODO,十万次数据测试
HashMap hashMap =new HashMap();
hashMap.put("001", 1.00);
hashMap.put("002", 2.00);
myHashMap.put("112", hashMap);
}
for (int i =0; i <100000; i++){ // TODO,十万次数据测试
HashMap hashMap =new HashMap();
hashMap.put("001", 1.00);
hashMap.put("002", 2.00);
myHashMap.put("11112", hashMap);
}
System.out.println(myHashMap);
输出的结果是:
{11={001=100000.0, 002=200000.0}, 111={001=100000.0, 002=200000.0}, 112={001=100000.0, 002=200000.0}, 11112={001=100000.0, 002=200000.0}}
用时0.47S。
用一个千万循环用时不到2S。