Arrange The Map To Obtain The key Associated With The Maximum Value.

Therefore, the task is to retrieve a few records from the Opportunity object, including the OwnerId and Id fields. For various records, there could be different owners. Our goal is to identify the OwnerId associated with the highest number of records and determine the count of those 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!

  1. Get the values from the map using mapObject.keySet() and store it in a list.
  2. Sort the list using `sort()` method.
  3. 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.

List<Opportunity> oppty = [SELECT Id, OwnerId, StageName, Name FROM Opportunity];
map<Id, Integer> oppty_map = new map<Id, Integer>();

for(Opportunity o : oppty){
    if(oppty_map.containsKey(o.OwnerId)){
        oppty_map.put(o.OwnerId, oppty_map.get(o.OwnerId) + 1);    
    }else{
        oppty_map.put(o.OwnerId, 1);
    }
}

//create a map with key as ownerId and value as the count 
System.debug(' 🚀 ' +oppty_map);

List<Integer> i_values = oppty_map.values();
i_values.sort();

//get the max value of the count
Integer i_max_value = i_values[(i_values.size()-1)];

for(String s : oppty_map.keySet()){
    Integer oppty_map_value = oppty_map.get(s);

    if(oppty_map_value == i_max_value){
        System.debug(' Id is ' + s + ' value is ' + oppty_map_value);
    }

}

I’ve come across other solutions as well (after successfully solving it on my own, of course :p). I observed that many of these solutions utilized wrapper classes. Wrapper classes are unnecessary unless you require a list of all sorted (ascending/descending) entries, such as OwnerId or count.