来一个俄罗斯Hash套娃

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。

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。