List<Account> ls = [select Id,Name from Account];
Map<Id, Account> m = new Map<Id, Account>(ls);
PutAll
Map<String, String> map1 = new Map<String, String>();
map1.put('Red','FF0000');
Map<String, String> map2 = new Map<String, String>();
map2.put('Blue','0000FF');
// Add map1 entries to map2
map2.putAll(map1);
System.assertEquals(2, map2.size());
List<Account> accts = new List<Account>();
accts.add(new Account(Name='Account1'));
accts.add(new Account(Name='Account2'));
// Insert accounts so their IDs are populated.
insert accts;
Map<Id, Account> m = new Map<Id, Account>();
// Add all the records to the map.
m.putAll(accts);
System.assertEquals(2, m.size());
you can add values through list(if the value is sobject), you have three ways 1.map<id,account> mp=new map<id,account>([select name from account limit 5]); 2. list<account> l=[select name from account limit 5]; map<id,account> mp1=new map<id,account>(ls); 3. using putall(listofsobject); map<id,account> mp2=new map<id,account>(); mp2.putAll(l);
NOTE: all this three are possible only if the key is ID/string
Please check the below example:
Here if you use the List to remove then
Also go through the below links to understand the Collections concept.
https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_methods_system_map.htm#apex_System_Map_remove
http://share-salesforce.blogspot.in/2013/05/sfdc-data-collections-listsetmap.html
https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/langCon_apex_collections.htm
Please do let me know if it hels you.
Regards,
Mahesh
1) https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_methods_system_map.htm
2) https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/langCon_apex_collections_maps.htm
ADD:-
How to add List in Map in one go :-
PutAll REmove :- REmove list Let us know if this will help you
Thanks
Amit Chaudhary
above posts can helps you. if you are specific to any perticular complex requirement then throw that here.
shiva.sfdc.backup@gmail.com
1.map<id,account> mp=new map<id,account>([select name from account limit 5]);
2. list<account> l=[select name from account limit 5];
map<id,account> mp1=new map<id,account>(ls);
3. using putall(listofsobject);
map<id,account> mp2=new map<id,account>();
mp2.putAll(l);
NOTE: all this three are possible only if the key is ID/string
To add list into Map-: For adding List into Map you can also use putAll()method.
For removing element from Map you can use remove()method.
If you find your Solution then mark this as the best answer.
Thank you!
Regards
Suraj Tripathi