1

Is there an easy way to extract the list of objects from a map containing list of objects? For ex, below is an example map that I need to deal with.

map<Id, List<Contact>> accountWithContacts = new map<Id, List<Contact>>();

Assuming that this map is populated with an accountId and the contacts that belong to the accountId, how to extract the List from the map? I could not find any method in the map class that returns a list.

Can someone help?

2

There is no simple one-line method (as in JavaScript, where we can e.g. Array.prototype.flat), its most simple form would be:

List<Contact> allContacts = new List<Contact>();
for(List<Contact> contacts: accountWithContacts.values()) {
  allContacts.addAll(contacts);
}
3
  • 1
    Needs addAll? – Keith C Apr 11 at 8:55
  • @KeithC Whoops. Fixed. Thanks for the catch. – sfdcfox Apr 11 at 14:56
  • Thank you very much. – Balaji Pooruli Apr 13 at 4:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.