0

I have a map which I want to sort the results in ASC order

Let's say that yearToDate is holding the below result

The result I have in yearToDate is

yearToDate::{Year 1=2023-09-15 00:00:00, Year 2=2024-03-15 00:00:00}
yearToDate = new Map<String, Decimal>();

and I am running the result to build another Map data

        yearToDate = new Map<String, Date> ();
        dateToDecimal = new Map<String, Decimal> ();
        for (String eKey : yearToDate.keySet()) {
        String key = 'Total ' + getMonthName(yearToDate.get(eKey)) + ' ' + yearToDate.get(eKey).year();
        dateToDecimal.put(key, yearToSum.get(eKey));
    }


    public static String getMonthName(Date value)
{
    return Datetime.newInstance(value, Time.newInstance(0, 0, 0, 0)).format('MMMM');
}

In the above example, I am getting the result as

dateToDecimal::{Total March 2024=12000.00, Total September 2023=6265.67}

The expected result would be like

dateToDecimal::{Total September 2023=6265.67, Total March 2024=12000.00}

I don't see any examples as well to sort this result in the correct order. Any help would be appreciated. Thank you

2
  • If possible please share the full code. Sep 8 at 9:15
  • I added the required code in my question. To say it simple, yearToDate is something I am trying to show it in different format. If you check the yearToDate, it is 2023-09-15. All I am doing it showing it as Total September 2023.
    – KSL
    Sep 8 at 9:22

1 Answer 1

1

Maps and Sets in Apex have a deterministic order, which means that the order you put elements in them is the order they are iterated over.

For example:

Map<String, String> testMap = new Map<String, String>();
testMap.put('Stack', 'Exchange');
testMap.put('Sales', 'Force');
for(String key : testMap.keySet()){
    //'Stack' will always come before 'Sales'
}

So in your example, as long as the elements are in the right order in your first Map, when you iterate over the keys, they will stay in that order. And they will be in that order in your new Map.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .