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
Case ManagerCase Manager 

Setting custom Keys in a Map

Below is my code which sets Id of Attachment as the Key but how do I set ParentId as a Key in that Map, how do I get that?

Map<Id, Attachment> mapAtt = new Map<Id, Attachment>([Select ParentId, Id From Attachment]);
Best Answer chosen by Case Manager
BalajiRanganathanBalajiRanganathan
if you want to have parent id as the key, then the value should be List<Attachment> not <Attachment> as one parent can have multiple attachments.

Map <String, List <Attachment>> myMap = new Map <String, List <Attachment>>();

for (Attachment attach:  [select Id, ParentId from Attachment]) {
   List<Attachment> attachments = myMap.get(attach.ParentId);
   if (attachments == null) {
     attachments = new List<String>();
     myMap.put(account.ParentId, attachments ;
   }
  attachments.add(attach.id);
}

 

All Answers

jayjaysjayjays
Hi,

there is no way to do this with one line, you will need to create a list and then loop through the list and add them to a map.

List<Attachment> attachmentList = [select Id, ParentId from Attachment];
map<id,Attachment> mapAtt = new map<id,Attachment>();
for(Attachment a:attachmentList){
    mapAtt.put(a.ParentId,a);
}

Thanks,
J.
BalajiRanganathanBalajiRanganathan
if you want to have parent id as the key, then the value should be List<Attachment> not <Attachment> as one parent can have multiple attachments.

Map <String, List <Attachment>> myMap = new Map <String, List <Attachment>>();

for (Attachment attach:  [select Id, ParentId from Attachment]) {
   List<Attachment> attachments = myMap.get(attach.ParentId);
   if (attachments == null) {
     attachments = new List<String>();
     myMap.put(account.ParentId, attachments ;
   }
  attachments.add(attach.id);
}

 
This was selected as the best answer
JeeTJeeT

I liked the approach of Balaji.
Here i am adding few corrections to his code, which works fine.

Map <String, List <Attachment>> myMap = new Map <String, List <Attachment>>();

for (Attachment attach:  [select Id, ParentId from Attachment ORDER BY ParentId]) {
   List<Attachment> attachments = myMap.get(attach.ParentId);
   if (attachments == null) {
     attachments = new List<Attachment>();
     attachments.add(attach);
     myMap.put(attach.ParentId, attachments) ;
   }else
  		attachments.add(attach);
}
BalajiRanganathanBalajiRanganathan

JEET, We dont need else, the line attachments.add(attach); is common and present in both if and else which can be taken out.