Reputation: 197
Hi I've a Map variable defined as follow:
Map<String,List<Event>> myMap = new HashMap<String,List<Event>>();
Lets say the (key:value) pairs are (abc:(x1,x2,x3)), (pqr:(x2,x4,x5)) and (xyz:(x4,x2,x9)).
Now, to remove we would be doing myMap.remove("pqr"), but that would remove the whole (key:value) pair set. But what I want is to just remove x5 in the set(x2,x4,x5) so that it leads to (pqr:(x2,x4)).
Please help me out in achieving this by suggesting some efficient ways to do so.
Upvotes: 1
Views: 673
Reputation: 4111
I am not aware of your full specs and reqs, but in order to decide on the structure used to store Events, you have to consider if duplicates or/and ordering are a requirement too.
Regarding efficiency, due to the fact that you need to search for an Object (to remove it), I would go with a
Map<String, Set<Event>> myMap = new HashMap<String, Set<Event>>();
or Multimap
from Guava.
If ordering is not of your concern, use HashSet<Event>
O(1) on add/remove
If natural ordering is required, use a TreeSet<Event>
O(logn) on add/remove
If insertion ordering is required, use a LinkedHashSet<Event>
O(1) on add/remove
Note: If you accept duplicates (which would be a good reason for choosing a List
over a Set
) the myMap.get(pqr).remove(x5);
would only remove the first occurence of this object. If you need to remove every occurence of x5
, then the following will work:
myMap.get(pqr).removeAll(Collections.singleton(x5));
Upvotes: 0
Reputation: 1342
I don't know if you can really do this (meaning config restrictions) but it seems that you have some kind of MultiMap
requirements.
I would suggest (if you can) to take a look on some MultiMap implementations, for example Guava. See related here or here
Upvotes: 0
Reputation: 1455
Considering the values to be ArrayList, you'll have to get the value of the key "pqr" and remove the data from the arraylist as answered above.
Upvotes: 1
Reputation: 746
myMap.put(key, value) will update the key, value pairing (and return the original value), so I would suggest just putting the new values you want in the map.
Upvotes: 0