Rolodecks
Rolodecks

Reputation: 396

Working with an Unordered List to calculate team stats

I'm working on a Sports program in which I have an Unordered List which contains multiple Player objects. These player objects are players for a basketball team and have attributes for Team(string), Total points scored(int), etc.

I am currently trying to write a method that will calculate the highest scoring team in the league. So my list has multiple player objects each with their individual total points scored and I'm trying to use this to figure out the team that has scored the most points.

I can easily calculate the player with the most points by looping through the list and finding the highest point value and then looping again to find players who have scored = to the highest value found in the previous loop. The problem is I don't know how to do this with the whole team, especially since all point values now must belong to a team.

Thanks

Upvotes: 0

Views: 279

Answers (1)

Simon Arsenault
Simon Arsenault

Reputation: 1845

Using a Map, you can do something like this:

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());
}

You can iterate over the map like this:

for (Map.Entry<String, Integer> teamPoints: teamsPoints.entrySet()) 
{
    System.out.println("Team = " + teamPoints.getKey() + ", Total points= " + teamPoints.getValue());
}

Upvotes: 1

Related Questions