Getting the newly added , deleted , modified values in hashmap at a particular state

◇◆丶佛笑我妖孽 提交于 2020-01-15 12:39:13

问题


I have an application , which operates on the hashmap at stages , in the sense it adds/deletes/modifies keys in different classes . Thought of creating wrapper class by extending the Map class . And Hacking the predefined put and remove methods .

STAGE 1 :

HashMap<String, String> hashMap = new HashMap<>();
hashMap.put("Key1","Value1");
hashMap.put("Key2","Value2");
hashMap.put("Key3","Value3");
hashMap.put("Key4", "Value4");

Desired Result :
Added:
Key1 : Value1
Key2 : Value2
Key3 : Value3
Key4 : Value4

STAGE 2:

hashMap.remove("Key1");

Desired Result :
Removed:
Key1 : Value1

STAGE 3:

hashMap.put("Key2", "ChangedValue");

Desired Result :
Modified :
Key2 : ChangedValue

What would be the best way or best logic to get only the diff ? The dataStructure HASHMAP is fixed .


回答1:


The simplest way is to extend HashMap to your own class, and record the changes:

class RecordHashMap extends HashMap<String,String> {
    private List<String[]> changes;

    public RecordHashMap() {
      super();
      changes = new ArrayList<String[]>();
    }

    @Override
    public String put(String key, String value) {

        if (containsKey(key)) {
            changes.add(new String[]{"modified",key,value});
        } else {
            changes.add(new String[]{"added",key,value});
        }
        return super.put(key, value);
     }

     @Override
     public String remove(Object key) {
         if (containsKey(key)) {
             String value = get(key);
             changes.add (new String[]{"removed",(String)key,value});
         }
         return super.remove(key);
     }

     public List<String[]> getChanges() {

         return changes;
    }
}

This way you can always check the last change, as they are all recorded. You can of course print them out as you record them - or later. You can add an index counter (to allow to only look at x recent changes), since you store them in an array list.



来源:https://stackoverflow.com/questions/45614982/getting-the-newly-added-deleted-modified-values-in-hashmap-at-a-particular-s

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!