I have a List
of objects, where each object has a number of votes, like so:
Object Votes
o1 5
o2 4
o3 3
o4 3
I want to rank each one (not just sort) based on the number of votes and create a Map
using the result. So the result would be:
Object Votes Rank
o1 5 1
o2 4 2
o3 3 3
o4 3 3
So you can see that o3 and o4 have the same rank because they have the same number of votes. Is there a fast implementation that would do this?
First Collections.sort the list, then iterate through the list. If the number of votes has changed since the last object, increase the rank, if the the votes count is the same, don't then add the object/rank to your map.
// Not tested, but it should give you the right idea.
Collections.sort(myList); // you may need to use a comparator here if your objects don't implement Comparable
int rank = 0;
int lastVotes = -1;
for (MyObject o : list)
{
if (o.getVotes() != lastVotes)
{
rank += 1;
}
myMap.put(o, rank);
lastVotes = o.getVotes();
}