Game CSV Sum with Map
Chuchu and Xyz are playing a game. But this time they've invited their friends!
They've written down their scores in a String
like this:
Xyz, 10
Chuchu,5
Sheldon,6
Xyz, 20
Lulu,8
Xyz, 4
The winner of the game is the player with the most total points. For the game above, the winner is Xyz, since she scored 34 points to Chuchu's 5, Sheldon's 6, and Lulu's 8. Note that zero is a valid number of points to have scored and should not be treated separately.
Create a public class Question with a single public static
method called winner
that determines the winner of
the game.
It accepts a single String
argument containing CSV records as shown above and should return
a String
containing the winner. If any two players earn the maximum score you should return "Tie".
A few notes.
First, you'll want to use both split
and trim
, two of our familiar functions for working with String
data.
Second, while each line will contain a record, there may be extra whitespace surrounding each record.
(The data was entered by happy animals.)
Third, recall that you can use Integer.parseInt
to convert a String
to an int
.
Fourth, if the String
passed is null
or empty you should return null
.
Finally, unlike the previous version of this problem Chuchu and Xyz are not the only players! They have many friends, some with strange names. So the participants will be different from game to game.
This is a great problem to solve using a map. Here's a solution approach:
- Parse the CSV and combine all the scores into a map, totaling the score for each player as you go
- Loop over the map to compute the maximum
You may need to examine the map documentation. But as a helpful note, the keySet
Map
function will return all
of the keys in the map, which you can iterate over: