Map – retainAll: Another way to avoid Null Pointer Exception while dealing with Map

Map<Id, Contact> mapAccIdToCont = getAccountToContactMap();//Predefined Map
List<Id> lstAccId = getAccountIds();//Predefined Account Id List

//1. Assume mapAccIdToCont has 50 Account Ids
//2. Assume lstAccId has 100 Account Ids
//3. Assume mapAccIdToCont.keySet() and lstAccId has common Account Ids. But not all of the Ids in mapAccIdToCont.keySet() are available in lstAccId

//Iterating over the list of AccountIds and accessing values from the Map may lead to Null Pointer Exception, if the null check is not done properly using the keywords like "containsKey". Using "retainAll", we can avoid such circumstances.

Set<Id> setAccId = new Set<Id>(lstAccountId).retainAll(mapAccIdToCont.keySet());//Forming a set of Account Ids from lstAccountId. These account ids are also available in the Map