Drakosha
Drakosha

Reputation: 12165

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?

Upvotes: 9

Views: 21352

Answers (4)

Sign
Sign

Reputation: 1959

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.

Upvotes: 8

Mark Byers
Mark Byers

Reputation: 838276

If you have a ConcurrentMap<K, V> there is the method putIfAbsent:

If the specified key is not already associated with a value, associate it with the given value. This is equivalent to

if (!map.containsKey(key))
    return map.put(key, value);
else
    return map.get(key);

except that the action is performed atomically.

However this method does not exist on Map<K, V>.

Upvotes: 5

anubhava
anubhava

Reputation: 785196

I don't think your proposed code is inefficient. See if key is already there in Map then its a single map look-up. And even for the cases when key is not found there are not 2 searches. Only 1 search and 1 insert into Map.

Upvotes: 1

paulsm4
paulsm4

Reputation: 121669

I don't think there's any way around checking "contains()" to see whether or not the key exists or not.

Look here to see if this might be an alternative for you:

What happens when a duplicate key is put into a HashMap?

Upvotes: 0

Related Questions