One line code to Add records to list and Map apex

 Sometimes, we need to query records from database and have take it into one Map, with id as a key and record as a value. for this, first we will query and loop thorough each record and add it to a map. but there is a straightaway to add it to map in single line of code. 

One line Add records to list

//Multi-line
Account ac;
List<Account> accountsList = new List<Account>();
accountsList.add(ac);

// Single line
Account ac;
List<Account> accountsList = new List<Account>{ac};

One line to Add records to Map

//Multi-line
Map<Id, Account> accountMap = new Map<Id, Account>();
List<Account> accountsList = [select Id, Name From Account];
for(Account ac: accountsList){
    accountMap.put(ac.Id, ac);
}

// Single line
List <Account> accountsList = [select Id, Name From Account];
Map <String, Account> accountMap = new Map <String, Account> (accountsList);
Labels:
Join the conversation