-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.

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

3 Comments

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.
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?
I got it. Great thanks again, @eyescream ! You are masterpiece!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.