I'd like to do the following functionality:
if (!map.contains(key)) {
map.put(key, val);
}
Update: Let's assume it's not HashMap
so the map is implemented as a tree of some kind.
However note that it's a little inefficient, since if we get into the if we actually search the map twice. I'd actually like to do something like that:
map.put_if_new_key(key, val);
Any idea how to do it in Java?
If you expect to be inserting new elements a vast majority of the time.
ValType temp = map.put(key, val);
if(temp != null)
map.put(key, temp);
I don't think it's a good idea in general, but it is worth considering if you can reason sufficiently about your use case.
Second thought on this if you can use a particular map implementation instead of just the map interface you could do this with a NavigableMap
Map sub = map.subMap(key, true, key, true);
if (!sub.contains(key)) {
sub.put(key, val);
}
Since the sub tree will be 0 or 1 nodes large there is no repeated work.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With