Skip to content

Instantly share code, notes, and snippets.

@msrivastav13
Last active July 20, 2017 15:13
Show Gist options
  • Save msrivastav13/6044144 to your computer and use it in GitHub Desktop.
Save msrivastav13/6044144 to your computer and use it in GitHub Desktop.
Maputil class shows an example on how to use Maps to form MAP<Id,List<Sobjects>>
Map < Id, List < Contact >> mapAccIdByCntlst = new Map < Id, List < Contact >> ();
for (Contact c: [Select Id, name, AccountId from Contact where AccountId != null]) {
// AccountId mapping with Contact List
if (mapAccIdByCntlst.containsKey(c.AccountId)) {
mapAccIdByCntlst.get(c.AccountId).add(c); //tricky part .Here map.get(key) is returning list and we are adding contacts to the list
} else {
List < Contact > lstcnts = new List < Contact > (); //Initialize list as no key is found before and first time we get key
lstcnts.add(c);
mapAccIdByCntlst.put(c.AccountId, lstcnts);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment