Why is record object with different id not used as key in Map?

I don’t quite understand this situation and I wonder, if somebody knows where is the problem.

I’ assigning in loop object as a key and simple number as his value:

Map<QuoteLineItem, Integer> mapa = new Map<QuoteLineItem, Integer>();

for (QuoteLineItem a : [SELECT Id FROM QuoteLineItem]) {
    mapa.put(a, 1);    
}

The query returns two objects: QuoteLineItem:{Id=0QL290000000NMjGAM} and QuoteLineItem:{Id=0QL290000000NMeGAM}, but map contains just:

{QuoteLineItem:{Id=0QL290000000NMjGAM}=1}

When i query also for description field, the map contains both records:

{
    QuoteLineItem:{Id=0QL290000000NMjGAM, Description=discount}=1, 
    QuoteLineItem:{Id=0QL290000000NMeGAM, Description=test apptus}=1
}

I’m aware, that key field is hashed, but these two records have different Ids, so they are not the same. And still, if we put same key into map, then the old key value should be rewritten with new value.

Answer

The code is working absolutely fine. The issue here is the system debug which prints the map. It is printing only the first value. I modified your code to also print the size and individual elements and it prints all of them. Try the below code (you might have to replace OpportunityLineItem with QuoteLineItem)

Map<OpportunityLineItem, Integer> mapa = new Map< OpportunityLineItem, Integer>();

for (OpportunityLineItem a : [SELECT Id FROM OpportunityLineItem limit 2]) {
    mapa.put(a, 1);    
}

System.debug('mapa: ' + mapa);

System.debug('Mapa size: ' + mapa.size());

for(opportunityLineItem oli : mapa.keySet()) {
  System.debug('OLI: ' + oli);
}

Result:

mapa: {OpportunityLineItem:{Id=00k4000000tDFxyAAE}=1}
Mapa size: 2
OLI: OpportunityLineItem:{Id=00k4000000tDFxyAAE}
OLI: OpportunityLineItem:{Id=00k4000000tDJKUAA2}

Attribution
Source : Link , Question Author : Martin.Kona , Answer Author : RajeshShah

Leave a Comment