Hello beautiful people,
I have a scenario where I am defining a Map with string key and a list. Now, I want to put values in a list one by one and also display them using the single Key. Example code -
Map<string,List<Account>> accountMap = new Map<string,List<Account>>();
//How to insert values. I am using this but no luck-
for(Account acc = [Select Id, Name from Account]){
accountMap(acc.Id,accList)
}
//Lets say we have data. How to display any **specific** value from the middle of the list. I am using this but no luck-
AccountList.get(id).get(3);
Please help.
Using account id as example is terrible idea because they'll be unique -> your lists would always have size 0. But yes, you should be able to do something like that.
Your stuff doesn't even compile, you can't use "=" in for(Account acc = [SELECT...])
.
Let's say you have accounts and some of them have duplicate names. This would be close to what you need:
Map<string,List<Account>> accountMap = new Map<string,List<Account>>();
for(Account acc : [SELECT Name, Description FROM Account LIMIT 100]){
if(accountMap.containsKey(acc.Name)){
accountMap.get(acc.Name).add(acc);
} else {
accountMap.put(acc.Id, new List<Account>{acc});
}
}
and then yes, if you'd have the key you can access accountMap.get('Acme Inc.')[0].Id