You need to sign in to do that
Don't have an account?
Case 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]);
Map<Id, Attachment> mapAtt = new Map<Id, Attachment>([Select ParentId, Id From Attachment]);
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
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.
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);
}
I liked the approach of Balaji.
Here i am adding few corrections to his code, which works fine.
JEET, We dont need else, the line attachments.add(attach); is common and present in both if and else which can be taken out.