Map throw error on duplicate insertion

map without duplicate keys java
hashmap duplicate keys
java map merge
map contains
what will happen if we put a key object in a hashmap which is already there
java map put

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?

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 {

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

Duplicate key insertion in a Hashmap (Java in General forum at , It will not insert it for sure. But do it throws any compile time or run time exception ?? Post by: Sridhar Santhanakrishnan , Ranch Hand. I want to know what happens when we try to insert a duplicate key in a Hashmap. It will not insert it for sure. But do it throws any compile time or run time exception ?? Did you tried to write a code before making such jugdement ? No. Map will insert the duplicate key also, but will replace the existing object. See the sample application below:-

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.

Updating Map values returns list exception (row with duplicate Id at , that there is not a duplicate Id being inserted on the map. It has to do not with the update DML or the Map itself, but with the Apex ListException: Row with duplicate Id at index: 1 It throws above duplicate record error. I have the checked above code its working fine when we are try to create the same record which is already in the DB it will throw error, now i want to merge the multiple duplicate records into 1 record for Account object whicg are already in the Data Base. Could you plase help me out on how work on this with Sample Example. As of above. Regards

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

Trigger to check Duplicate Email on Lead is not working when , your trigger runs on both before insert and before update. ids and see if its not the same lead and then throw the error.. hope the below code will work for you The map::insert() is a built-in function in C++ STL which is used to insert elements with a particular key in the map container. Syntax: iterator map_name.insert({key, element}) Parameters: The function accepts a pair that consists of a key and element which is to be inserted into the map container. The function does not insert the key and

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

SFML Game Development, exception will be thrown until a try—catch block catches it and reacts the map will refuse to insert our ID-resource pair, as it cannot contain duplicate keys. Extends the container by inserting new elements, effectively increasing the container size by the number of elements inserted. Because element keys in a map are unique, the insertion operation checks whether each inserted element has a key equivalent to the one of an element already in the container, and if so, the element is not inserted, returning an iterator to this existing element (if the

Collectors toMap duplicate key, A quick and practical guide to handling duplicate keys by using multimaps in As we can see, if we try to insert two values for the same key, the However, this verbose solution has multiple drawbacks and is prone to errors. 10) If nh is an empty node handle, does nothing and returns the end iterator.Otherwise, inserts the element owned by nh into the container, if the container doesn't already contain an element with a key equivalent to nh. key (), and returns the iterator pointing to the element with key equivalent to nh. key (regardless of whether the insert succeeded or failed).

How to Store Duplicate Keys in a Map in Java?, Note: If you see Many "Cannot insert duplicate key row in object" errors in execution history that references a Map named of RSBulkData, contact Support. Although Title:SqlException thrown while attempting Bulk Create trigger contactDuplicatePreventer on Contact(before insert, before update) { Map<String, Contact> contactMap = new Map<String, Contact>(); for (Contact Contact : { // Make sure we don't treat an email address that // isn't changing during an update as a duplicate.

Replication Services (RS) Duplicate Key Warnings, It is throwing error: MySQLIntegrityConstraintViolationException: Duplicate entry '15' for key 'PRIMARY' Data: Our cdt has foreign key mapping as well. There were triggers which update history table when insertion or updation is done in  Below the apex trigger for contact duplicate prevention based on email, hope this will help you. trigger contactDuplicatePreventer on Contact (before insert, before update) { Map<String, Contact> contactMap =new Map<String, Contact>(); for (Contact contact :{

  • the code above will always throw a NullPointerException, since you didn't even initialise your temp Map. duplicates or not.
  • There's no need for a Map to have such a functionality, since you can always call if (temp.containsKey(1)) to avoid such an exception.
  • @Stultuske I know i did not initialize the map because i don't know with which implementation to implement it. It can be HashMap() or ImmutableMap or any other.
  • The Map interface defines the replacement behaviour of put - so any implementation that does something different would be in violation of that contract.
  • Also, to prevent having to check for duplicate value accross your application, I would suggest extending the HashMap class and overriding put method to check for duplicate and then only insert
  • we can use only the second solution when the map is being used by external library. But problem is it also fails silently. Or, we can throw RuntimeException.