List & Map
- johnsontitus
- May 26, 2020
- 1 min read
//Account a = new Account(name='Account14', Type='Prospect');
//Account b = new Account(name='Account15', Type='Prospect');
/*
//defining a list
Account [] accLst = new Account[]{a,b};
for(Account a : accLst){
System.debug(a.name);
}
System.debug(accLst[0].name);
*/
/*
//defining list
List<Account> actLst = new List<Account>{a,b};
for(Account a : actLst){
System.debug(a.name);
}
//defining list
List<Account> accs = [select name from Account];
//To add an object to the next available element of the List
accs.add(new Account(name='Account16'));
*/
/*
// Create a generic sObject variable.
List<sObject> sObj = Database.query('SELECT Id FROM Account LIMIT 1');
List<Account> aobjs = new List<Account>();
for(sObject a : sObj){
//typecasting generic object to Account Type
aobjs.add((Account)a);
}
for(Account at : aobjs){
System.debug(at.Id);
}
*/
Account a = new Account(name='Acme', BillingCity='New York');
Account b = new Account(name='Lakme', BillingCity='New Jersey');
Map<Integer, Account> mapAccount = new Map<Integer,Account>{};
mapAccount.put(1,a);
mapAccount.put(2,b);
//get the Account object mapped to key integer - 1
mapAccount.get(1).BillingCity='Mumbai';
//check the existence of a key
Boolean bo = mapAccount.containsKey(1);
Set<Integer> keyInt = new Set<Integer>();
//returns all keys that is stored in the Set object
keyInt = mapAccount.keySet();
for(Integer k : keyInt){
System.debug('keys are ' + k);
System.debug(mapAccount.get(k).name);
}
//Returns the number of key-value pairs in the map
System.debug(mapAccount.size());
//returns all values associated to the maps,
//in this instance all Account objects
System.debug(mapAccount.values());
for(Account a : mapAccount.values()){
System.debug(a.name);
}

Comments