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.

You can see the OwnerId and the count
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.
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 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).
Learn it by building it
Every course, every code repository, the discussion group and certificates of completion — one subscription.