[SalesForce] Duplicates in Map

Is it possible to create a Map with duplicate Key

Key          Value
Product 1    100
product 1    200
product 2    200
product 2    300

Scenario : I have a trigger on quote and have to find the listprice of quotelineitems which have the same product name

I constructed a map with (productname,quotelineitem.listprice)

I have custom setting to check if the map has the key "product name" and then add up all the values

The problem is that I cannot form the above map because I am forgetting the fact that maps cannot have duplicate KEYS 🙁

IS there a better way to approach this

Best Answer

Map of lists maybe?

List<Account> fakeQuotes = new List<Account>{
    new Account(Name = 'Prod 1', AnnualRevenue = 100),
    new Account(Name = 'Prod 2', AnnualRevenue = 200),
    new Account(Name = 'Prod 1', AnnualRevenue = 300),
    new Account(Name = 'Prod 2', AnnualRevenue = 400),
    new Account(Name = 'Prod 1', AnnualRevenue = 500)
};

Map<String, List<Double>> listPrices = new Map<String, List<Double>>();
for(Account a : fakeQuotes){
    List<Double> temp = listPrices.get(a.Name);
    if(temp == null) {
        listPrices.put(a.Name, new List<Double>{a.AnnualRevenue});
    } else {
        temp.add(a.AnnualRevenue);
    }
}

System.debug(listPrices); // {Prod 1=(100.0, 300.0, 500.0), Prod 2=(200.0, 400.0)}
Related Topic