| Author |
HashMap logic
|
trupti nigam
Ranch Hand
Joined: Jun 21, 2001
Posts: 602
|
|
I have two hashmaps.
HasMap1 has keys 100 , 200
HashMap2 has keys 200,300,400,100
I need to remove the elements with keys 300 and 400 which are also in HashMap1 from HashMap2. How to achieve that? I thought of different ways but the problem is even if I separate the duplicates keys how to make sure I remove only those from HashMap2.
thanks,
Trupti
|
 |
Campbell Ritchie
Sheriff
Joined: Oct 13, 2005
Posts: 32708
|
|
Draw a diagram on a piece of paper and the logic will become obvious.
You need to be specific. By “also in HashMap1” do you mean they have the same “V”s?
|
 |
Ashwini Kashyap
Ranch Hand
Joined: Aug 30, 2012
Posts: 61
|
|
Hi Trupti,
I think you should check out once the API for Hashmap here.
For reading keys of the map, use keySet(). Iterate through them and proceed like for instance:
if(hashMap1.get(key).equals(hashMap2.get(key)){
hashMap2.remove(key);
}
Thanks and Regards,
Ashwini Kashyap | akashyap@infocepts.com | www.infocepts.com
|
 |
trupti nigam
Ranch Hand
Joined: Jun 21, 2001
Posts: 602
|
|
Campbell Ritchie wrote:Draw a diagram on a piece of paper and the logic will become obvious.
You need to be specific. By “also in HashMap1” do you mean they have the same “V”s?
Yes the values are same.
|
 |
trupti nigam
Ranch Hand
Joined: Jun 21, 2001
Posts: 602
|
|
Ashwini Kashyap wrote:Hi Trupti,
I think you should check out once the API for Hashmap here.
For reading keys of the map, use keySet(). Iterate through them and proceed like for instance:
if(hashMap1.get(key).equals(hashMap2.get(key)){
hashMap2.remove(key);
}
Thanks and Regards,
Ashwini Kashyap | akashyap@infocepts.com | www.infocepts.com
I don't want to remove the duplicate key elements but the non dupe one.
|
 |
John Jai
Bartender
Joined: May 31, 2011
Posts: 1778
|
|
|
Alternatively instead of iterating, you can use the retainAll() method in Set interface. First get the key set of the second map and call retainAll() on it with the first map's keys. Check methods - keySet() and retainAll()
|
 |
Ashwini Kashyap
Ranch Hand
Joined: Aug 30, 2012
Posts: 61
|
|
Yet its simple. Make use of !equals() i.e. not equals method.
Thanks and Regards,
Ashwini Kashyap | akashyap@infocepts.com | www.infocepts.com
|
 |
trupti nigam
Ranch Hand
Joined: Jun 21, 2001
Posts: 602
|
|
It was pretty simple. Here is the sample program.
|
 |
Paul Clapham
Bartender
Joined: Oct 14, 2005
Posts: 16483
|
|
I would prefer something more simple than that. Based on John Jai's comment, I would replace this:
by this:
|
 |
 |
|
|
subject: HashMap logic
|
|
|