There is a Map. At a beautiful moment, several of its Value can change, the keys of course remain in place. I need to get a card that would contain only those key-value pairs that have been changed.

enter image description here

I thought I would take keySet () and removeAll (), but the keys do not change, so I’ll get an empty result.

I thought I would get the values ​​() from two maps and do removeAll (), in this case, of course, I get pairs that have changed, but without keys. Just bare values ​​without keys are not suitable. How to be?

  • one
    This is what you call dictionaries cards? - Zelta
  • And not only me. - arg
  • Well, just when you change an element, save its key somewhere in the set, then get the elements by these keys. By itself hashtable should not store such information. - Zelta
  • one
    Well, you have your own atmosphere there ... - Zelta
  • Map changes very deep in the code. I can only get it and copy it. - arg

1 answer 1

I do not know if you can use third-party libraries, so I suggest this option:

Map<String, Object> a = new HashMap<String, Object>(); a.put("1", "one"); a.put("2", "two"); a.put("3", "three"); Map<String, Object> b = new HashMap<String, Object>(a); b.put("1", "ein"); System.out.println("before: " + a); System.out.println("after: " + b); Map<String, Object> c = new HashMap<String, Object>(); for (Map.Entry<String, Object> e : a.entrySet()) { String key = e.getKey(); if (!e.getValue().equals(b.get(key))) { c.put(key, b.get(key)); } } System.out.println("result: " + c); 
  • Well, really there is a minus. This will not work if I have not redefined the equals method for value objects, but I was lucky - I store it in string values. What did you want to say about third-party libraries? - arg
  • 2
    @argamidon I mean guava . entriesDiffering() - The entries with the same keys, but differing values. - Alexey