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?
 
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