-1

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.

Praveen Behera
  • 444
  • 2
  • 8
  • 17

1 Answers1

1

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

eyescream
  • 18,088
  • 2
  • 34
  • 46
  • Thanks eyescream as usual. 1 quick question in this line - ```If(accountMap.containsKey(acc.Name))``` , Why did we write this? we did not assign a key value in the map yet. – Praveen Behera May 09 '22 at 17:15
  • 1
    yet. But this will run in a loop. I you have 3 accounts with identical name (or whatever your unique key is) - you want to replace them in the map, make last one "winner"? Or do you want to check and add to existing list if something is already there? – eyescream May 09 '22 at 17:54
  • I got it. Great thanks again, @eyescream ! You are masterpiece! – Praveen Behera May 10 '22 at 15:01