Java map problem

Associate
Joined
19 Jun 2006
Posts
162
Location
Swansea, Wales
Hey guys,

I don't use maps much so there is probably an easy solution to this problem i don't know of...

I have a map with many unique keys but the keys only map to a few distinct values.

E.g.

Key 1 => abc
Key 2 => abc
Key 3 => xyz
Key 4 => abc
Key 5 => abc
Key 6 => xyz

Now if i want to remove a key then i just use map.remove(key) but what do i do if i want to remove all they keys that contain a specific value?

So, using my previous example, i want to remove "abc" so i need to loop through and remove key1, key2, key4 and key5.

I can't see how to loop through a map examining each value so it seems difficult.

Any ideas?
 
You can do that using an iterator. There may be a better way but this is the way that I know.

Something like:

Code:
Iterator it = map.Iterator();
while(it.hasNext())
{
if (it.next()=="abc")
it.remove();
}
 
Can you have duplicate values in a map? I was under the impression that the key was derived from the values and if you had the same value entered twice it would produce the same key and it would not be added.
 
maxpower is right, you can have duplicates but only if the keys are unique. you will have to use an iterator to remove all duplicate values, but they are quite easy to use.
 
Just a note I found at leepoint.net ...

Maps do not provide an iterator() method as do Lists and Sets. A Set of either keys (keySet()) or key-value Map.Entry elements (entrySet()) can be obtained from the Map, and one can iterate over that.

So my code ended up as...

Code:
Iterator it = portMap.values().iterator();
while (it.hasNext()) {
  if (it.next().equals(id)) {
    it.remove();
  }
}
 
Back
Top Bottom