I have a list of the string contains duplicate values and I want to retain the duplicate value also in the Map and my code is below my list contains only 2 values while iterating in for loop I want all four values in Map with key and values and my code is below .please help. Thanks in advance

      List<object> arr = new List<object>({COMPANYID=388, 
        {COMPANYID=388, CONTACTID=6663,ROLE_NAME=Developer},
        {COMPANYID=399, CONTACTID=10358, ROLE_NAME=Engineer},
        {COMPANYID=399, CONTACTID=10357, ROLE_NAME=Engineer});
      Map<String,object> mp_StrObj = new Map<String,object>();
      Map<string,object> FinalMap = new Map<string ,object>();

                for(object obj :arr)
                    System.debug('Role: '+obj);
                    mp_StrObj = (Map<string,object>)obj;

        System.debug('FinalMap '+FinalMap);

when I print the final map it shows only 2 objects.but I want all the four in FinalMap Map


1 Answer 1


A map always has unique key values. Where you have multiple objects that could share the same key, you must make the map's values allow for this. For example, here I would make your Map<string,object> FinalMap actually Map<string,List<Object>> finalMap. Now you would populate it thus:

for  (Object obj : arr) {
    List<Object> entries = finalMap.get(obj.COMPANY_ID);

    if (entries == null) {
        finalMap.put(obj.COMPANY_ID, New List<Object>{ obj });
    } else {

At this point all arr objects sharing the same company ID can be fetched from the map using the company ID value.

Note that I have ignored some typing issues since your question does not clarify the type of object you hold here.

  • Comments are not for extended discussion; this conversation has been moved to chat.
    – David Reed
    Jan 24, 2021 at 16:04

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .