Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Map throw error on duplicate insertion

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?

like image 482
Belphegor21 Avatar asked Oct 15 '25 23:10

Belphegor21


2 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 + "'.");
});
like image 60
benez Avatar answered Oct 18 '25 11:10

benez


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 ;)

like image 39
Hrabosch Avatar answered Oct 18 '25 13:10

Hrabosch