function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Manish Tripathi 20Manish Tripathi 20 

I have a map in with I stored String vs List of Contact , and Now I am iterating over this map , on keyset, in inner for loop I am trying to add all values(Contacts) associated to a single key

I have a map in which I stored String vs List of Contact , and Now I am iterating over this map , on keyset. In inner for loop I am trying to add all values(Contacts) associated to a single key in a list, so that I can seperate contacts with email and without email in two lists ,but for-each loop works on single records , so I am trying to use counter ,so that I can identify values count and index, so that I can compare but not able to acheive this , Any help.
Main purpose is to merge duplicate contacts. 

   for(String cc:mapContact.KeySet()){
            Integer i=0;
            If(mapContact.get(cc).size()>0){
            for(Contact con:mapContact.get(cc)){
                if(con.Email!=null){
                    ccWithEmail.add(con);
                i++;
            }
            }
        }
Suraj Tripathi 47Suraj Tripathi 47
Hi Manish,
Greetings!

You can merge contact on the basis of the email field.
Map<String, List<Contact>> email_ListContact_Map = new Map<String, List<Contact>>
for(Contact con : [SELECT Id, Email FROM Contact]) {
    if(!email_ListContact_Map.containsKey(con.Email.toLowerCase())) {
        email_ListContact_Map.put(con.Email.toLowerCase(), new List<Contact>{con});
    }
    else {
        email_ListContact_Map.get(con.Email.toLowerCase()).add(con);
    }
}

Now, you have Map where the key is String and Value is a List of Contacts related to a key (email).

If you find your Solution then mark this as the best answer. 

Thank you!

Regards,
Suraj Tripathi