I am passing a list of opportunities (opplist) to a method. For each opportuntiy, I have to check the description field of its related account. And based on that field, I will add the respective list of opportunities to another opportunity lists. If description is 'Yes' then to 'yeslist, and if 'No' then to 'nolist'. In the method receiving the opplist, I added the below code.

public static List<Opportunities> samplemethod(List<Opportunity> opplist){

Set<Id> opptIds = (new Map<Id,SObject>(opplist)).keySet();

List<Opportunity> opp = [Select o.Id, o.AccountId, o.Account.Description from opportunity o where Id IN :opptIds] ; 
Map<sObject,sObject> OppMap = new Map<sObject,sObject>(opplist,opp);


Basically I want to map the opplist with the list having the description field for same corresponding IDs (Same record. opplist has original record passed to method and opp has record with description field .

My doubt is is there a way to keep sobject as both key and value pair in maps ? I am planing to iterate the map over for loop after this.

2 Answers 2


Not the way you have done it..

Map<sObject,sObject> OppMap = new Map<sObject,sObject>(opplist,opp);

If you want to use an sObject as a key go through this documentation once. sObject Map Considerations

Be cautious when using sObjects as map keys. Key matching for sObjects is based on the comparison of all sObject field values. If one or more field values change after adding an sObject to the map, attempting to retrieve this sObject from the map returns null. This is because the modified sObject isn’t found in the map due to different field values. This can occur if you explicitly change a field on the sObject, or if the sObject fields are implicitly changed by the system; for example, after inserting an sObject, the sObject variable has the ID field autofilled. Attempting to fetch this Object from a map to which it was added before the insert operation won’t yield the map entry

I can't get what you want to achieve by creating a Map like this.


You can use a similar logic like this;

List <Contact> Yes= new List<Contact>();
List <Contact> No= new List<Contact>();

List<Contact> lstContact=  [Select Account.Description from Contact];
List<String> lstString = new List<String>();
for (Contact con: lstContact) {
    if (con.Account.Description == 'Yes')
    else if (con.Account.Description == 'No')

You must log in to answer this question.

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