Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Put a value into the map in Java *without* updating existing value if exists

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?

like image 759
Drakosha Avatar asked Dec 09 '11 20:12

Drakosha


1 Answers

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.

like image 93
Sign Avatar answered Oct 19 '22 12:10

Sign