In collection we have,
1)List
2)Set
3)Map
List==> 1)Ordered
2)Can store duplicate
3)We can perform dml operations on list
Syntax:
- list<object> listName=new list<object>(); // List of any object...
- list<String> listName=new list<String>(); // List of string...
Method available with list,
get(); // accessing element from list...
add(); // adding element to list...
size(); // checking size of list...
clear(); // clearing list...
Declaring list for account object,
==> List<Account> accList=new List<Account>(); //List of account...
Adding elements to list,
==> accList.add(someinstance); //Some object instance
Accessing elements from list,
==> accList.get(0); // first element
Structure of list is,
Location: Index 0 Index 1 Index 2 Index 3
Values: 1 2 3 4
Set==>1)Unordered
2)Duplicates are not allowed in set
Methods available with set are,
add(); // adding element to set...
remove(); // removing elemnt from set...
contains(); // checking element inside set...
Syntax:
- Set<id> idList=new Set<id>(); //set of id's
idList.add(1);
Removing added element from Set,
idList.remove(1);
Map==> Map is used to store key value pair.
Method available with map are,
Keyset();
Values();
get(Keyid);
put(key,value);
containskey(key);
clear();
size();
clone();
isEmpty();
remove(key);
Syntax:
Map can be used in different ways some listed below,
- Map<string,string> mapName=new map<string,string>();
- Map<integer, string> mapName = new Map<integer, string>();
- Map<integer, objectName> mapName = new Map<integer, objectName>();
- Map<string,list<objectName> mapName= new
- Map<string,list<objectName> ();
Sample ex:
1)For storing contact in map with unique number.
Map<integer, contact> mapName = new Map<integer, contact>();
contact obj=[select id,name from contact limit 1];
mapName.put(1,obj);
2)For storing Child record list related to parent record.
Map<String,list<contact>> accountWithContactsMap= new Map<String,list<contact>>();
Map<String,list<contact>> accountWithContactsMap= new Map<String,list<contact>>();
List<Account> accountList=new List<Account>();
accountList=[Select id,Name,(Select id,Name from Contacts) from Account];
for(Account obj:accountList)
{
if(obj.Contacts.size() >=1)
{
if(!accountWithContactsMap.containsKey(obj.id))
{
accountWithContactsMap.put(obj.id,obj.Contacts);
}
}
}
To get all Contacts related to particular Account.
Account obj= new Account();
obj=[Select id,name from account limit 1];
List<Contact> conList1=new List<Contact> conList1();
if(accountWithContactsMap.containsKey(obj.id))
{
conList1=accountWithContactsMap1.get(obj.id);
}
good explanation of maps
ReplyDeleteNice article.
ReplyDeleteHow can we use clone and deepclone for standard datatypes in a Map?