gpt4 book ai didi

java - 对列表中的对象进行排名

转载 作者:行者123 更新时间:2023-11-30 04:29:51 31 4
gpt4 key购买 nike

我有一个对象的列表,其中每个对象都有一定数量的投票,如下所示:

Object  Votes 
o1 5
o2 4
o3 3
o4 3

我想根据票数对每个投票进行排名(不仅仅是排序),并使用结果创建一个Map。所以结果是:

Object  Votes  Rank
o1 5 1
o2 4 2
o3 3 3
o4 3 3

因此您可以看到 o3 和 o4 具有相同的排名,因为它们具有相同的票数。有没有快速的实现可以做到这一点?

最佳答案

首先对列表进行 Collections.sort,然后迭代列表。如果自最后一个对象以来票数发生了变化,则增加排名,如果票数相同,则不要将对象/排名添加到您的 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();
}

关于java - 对列表中的对象进行排名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14891839/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com