So, the question is, get few records from Opportunity object, fields included are OwnerId, Id.
Now, for different records there might be different owners. We would need the OwnerId who owns most no of records and the count of the records.
It's obvious that we would have to use Lists and Maps.
Also, it's pretty straight forward to just get the max value form the bunch of values from the map.
These are the steps involved!
- Get the values from the map using
mapObject.keySet()and store it in a list.
- Sort the list using `sort()` method.
- Get the last element in the list.
But, how can we get the key associated with the maximum value?
That’s the catch!
In a map when we insert any entries they will be pushed in ascending order, meaning, though we tend to insert random keys, they will be sorted in ascending order.
I just wanted to see if I can crack this.
Well, I was able to crack it. Here's how I did it.
I have seen others solutions too (obviously after I cracked this on my own :p) I noticed many of the solutions were using wrapper classes. You wouldn’t need wrapper classes until you need list of all the sorted(ascending/descending) entries(OwnerId/count).