Problem overview
The method countVote receives votes, a HashMap from names to how many votes each person has, and the name on a new vote. It gives that person one more vote and returns the map. A person with no votes yet is not in the map; they start from 0, so after this vote they have 1. The map may be empty, and the order of entries does not matter.
With Ana at 3 and Ben at 5, a vote for Ana makes it 4. A vote for Cara, who is missing, adds Cara with 1. In an empty map, the first vote for Max gives Max 1.
Approach
Both cases, a known name and a new one, follow the same rule: new count = old count + 1, where the old count is 0 for a missing name. If you read the old count with get, a missing name gives null, and unboxing that into an int throws a NullPointerException. getOrDefault(name, 0) returns the stored count, or 0 when the name is missing, and it does not add the key by itself. Then one put stores the new count: it adds a new key, or replaces the value of an existing one. No if is needed.
Step by step
- Read the count so far:
int count = votes.getOrDefault(name, 0);. - Store the increased count:
votes.put(name, count + 1). - Return
votes. Only the entry fornamechanged.
The solution in Java
class Solution {
public HashMap<String, Integer> countVote(HashMap<String, Integer> votes, String name) {
int count = votes.getOrDefault(name, 0);
votes.put(name, count + 1);
return votes;
}
}
Details worth knowing:
- The map holds
Integerobjects, and Java converts them to and fromintautomatically (boxing and unboxing). That conversion is why anullread is a problem and a default is the fix. - The method changes the map it receives and returns that same map.
count + 1is computed beforeputruns, so the same line works whether the key is new or old.
Edge cases and common mistakes
- Using get for the first read.
int count = votes.get(name);works for Ana but throwsNullPointerExceptionfor Cara, who has no entry. - Storing the old count.
put(name, count)without the+ 1never changes anything. - Forgetting to put. Computing
count + 1and not storing it leaves the map as it was. - Empty map.
getOrDefaultreturns 0, so the first vote creates the entry with 1.
One pattern for two jobs
Read with a default, add one, store: this three-step shape appears whenever you count things in a map, such as letters in a word or votes in a poll. The default of 0 is what makes the first occurrence behave like every later one. The map returned is the same object that was passed in: after the call, votes already holds the new count.
Testing
Results, printed as key: value lines sorted by key, as the lesson's tests print them:
- Ana 3, Ben 5, vote for Ana gives Ana: 4, Ben: 5.
- Ana 3, Ben 5, vote for Cara gives Ana: 3, Ben: 5, Cara: 1.
- An empty map, vote for Max gives Max: 1.
