Maps are an example of an unordered collection, which cannot be sorted.
However, If you're open to writing code and spending additional time developing your idea, you can build something that should work.
From what I see, you don't absolutely require a Map, it was just the closest feature provided by Salesforce that you could find.
Instead of a Map, I'd suggest making an Apex class to hold your data that implements the comparable interface. You can then store these results in a List (which is an ordered collection).
A quick example to get you going
class DatePlusInteger implements Comparable{
public Date myDate;
public Integer count;
public Integer compareTo(Object compareObj){
DatePlusInteger comparisonTarget = (DatePlusInteger)compareObj;
if(comparisonTarget.Integer === count){
return 0;
}else if(comparisonTarget.Integer < count){
// This instance of our object has a greater count than the one
// we are comparing against. So, return positive 1
return 1;
} else {
return -1;
}
}
}
Implementing the Comparable interface will allow you to call List.sort()
. Doing so will sort the records in ascending order, meaning that your largest count will be the last element of your list.
The last element of a list is pretty easily retrieved using the List's size()
method
// Apex collections are 0-indexed, so when using size(), we must subtract 1
// Otherwise, we'd get an out-of-bounds exception
Object lastElement = someList[someList.size() - 1];
I'm fairly certain that retrieving an object from a List returns a reference to the object instance in that list. To put it simply, that means that you should be able to grab the date, decrement the count, and not have to worry about anything else.
lastElement.myDate;
lastElement.count -= 1;
A slightly better approach would be to add a getter to DatePlusCount
that would take care of the decrementing for you.
class DatePlusCount{
/* other lines omitted */
public Date getDate(){
count -=1;
return myDate;
}
}
usage is pretty simple
// Assuming List<DatePlusCount> myList is initialized elsewhere...
myList.sort();
Date targetDate = myList[myList.size()-1].getDate();
The only thing left that you'd need to concern yourself with would be to make sure that you always call sort()
on the List every single time before trying to retrieve the Date
associated with the maximum count.
Swapping the return 1;
and return -1;
in the compareTo(Object compareObj)
method could make things even simpler still. That should effectively cause the list sorting to return in decending order, meaning the max value would be at index 0;