Map throw error on duplicate insertion

Viewed 7300

I am creating a Map with stores some data and i want the map to throw an exception if a duplicate value is tried to insert.

Map <Integer, String> temp;
temp.put(1, "hi");
temp.put(1, "hello");

Here this map should throw an error since a key '1' is already present. It can throw an error or does not compile. Is there any map which has said functionality?

4 Answers

Using a contains-check prior to the put-operation is not an atomic-operation and therefore not thread-safe. Additionally, the map has to be accessed twice each time you add an entry.

To avoid this, use one of the functional methods like merge or compute:

map.merge(key, value, (v1, v2) -> {
    throw new IllegalArgumentException("Duplicate key '" + key + "'.");
});

Map doesn't throw any error or exception while trying to add new value with a key that is present in the map. In that case old value is simply being replaced with a new value.

If you want to add a functionality that will throw an error in that situation, you can use

if(map.containsKey(yourKey)) // here your error action

Check containsKey method.

Map<Integer, String> map = new LinkedHashMap<>();

    map.put(1, "Value");
    if (map.containsKey(1)) {
        throw new Exception("Map already contains key 1");
    }

For your question, you can create your own implementation like:

public class MyCustomMap extends HashMap {

        @Override
        public Object put(Object key, Object value) {
            if (this.containsKey(key)) {
                System.out.println("Do whatevery you want when key exists.");
                return null;
            } else {
                return super.put(key, value);
            }
        }
    }

And then use it:

public static void main(String[] args) throws Exception {

        Map<Integer, String> map = new MyCustomMap();

        map.put(1, "Value");

        map.put(1, "Another value");

    }

Note: This is example, without null checking etc.

But please, always try to check JavaDoc or basic data structure use cases before asking here, I believe that on Google is a ton of examples ;)

Map.put returns the previous value associated with key, or null if there was no mapping for key. (A null return can also indicate that the map previously associated null with key, if the implementation supports null values.)

So you can do this:

public void addItem ( Integer key, String value ) throws Exception {
  String old = map.put( key, value );
  if ( old != null) {
     throw new Exception("Already exists!");
  }
}

Beware: in this code the new value is instered anyway, even though the key already existed, you cannot add null as it will throw an exception.

Related