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?
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 + "'.");
});
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 ;)
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