0

I want to implement a method that finds the equal keys of two given hash maps and store them in a third hash map, along with add their respective values. Supposing we have 3 hashmaps HashMap<String, Integer> h1, h2, h3, take this example:

h1 = {mostly=2, than=4, half=7}
h2 = {mostly=10, go=5, half= 3, become=6}
h3 = interection(h1, h2)
result: h3 = {mostly=12, haf=10}

It's trivial how to do this using a brute-force method, i.e. by iterating on h1 and check the result of h2.containsKey(). Can someone suggest me an efficient way to implement such a method?

Thanks in advance.

Kapoios
  • 688
  • 7
  • 22
  • There is no way around iterating one of the sets. Pick the smaller one for iteration. – Sergey Kalinichenko Apr 29 '15 at 09:48
  • "retain all" I think does not solve your specific problem because you need to aggregate the values in both the maps. So it's not a duplicate question I think. And since you need to aggregate the values of the common keys there is no other way but to iterate the on values. – Tarun Gupta Apr 29 '15 at 09:56

0 Answers0