我正在开发一个 Sports 程序,其中有一个包含多个 Player 对象的无序列表。这些球员对象是篮球队的球员,具有球队(string)、总得分(int)等属性。
我目前正在尝试编写一种方法来计算联盟中得分最高的球队。因此,我的列表有多个玩家对象,每个对象都有各自的总得分,我试图用它来找出得分最高的团队。
我可以通过循环遍历列表并找到最高分值,然后再次循环查找得分 = 达到上一个循环中找到的最高值的玩家,轻松计算得分最高的玩家。问题是我不知道如何对整个团队执行此操作,特别是因为现在所有点值都必须属于一个团队。
谢谢
最佳答案
使用 map ,您可以执行以下操作:
Map<String, Integer> teamsPoints = new HashMap<String, Integer>();
for (Player player : players)
{
Integer teamPoints = teamsPoints.get(player.getTeamName());
if (teamPoints == null)
teamsPoints.put(player.getTeamName(), player.getPoints());
else
teamsPoints.put(player.getTeamName(), teamPoints + player.getPoints());
}
您可以像这样迭代 map :
for (Map.Entry<String, Integer> teamPoints: teamsPoints.entrySet())
{
System.out.println("Team = " + teamPoints.getKey() + ", Total points= " + teamPoints.getValue());
}
关于java - 使用无序列表来计算团队统计数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19554396/