import java.util.ArrayList; import java.util.Map; import java.util.TreeMap; /** * Holds the tally of votes for an election * * @author Scot Drysdale */ public class VoteTally { Map tally; /** * Construct a tally with no votes */ public VoteTally() { tally = new TreeMap(); } /** * Record a vote for a candidate. If candidate not found, * add that candidate with a 1 vote total. * @param candidate the name of the candidate to receive a vote */ public void recordVote(String candidate) { Integer currentTally = tally.get(candidate); if(currentTally != null) { tally.put(candidate, currentTally + 1); } else tally.put(candidate, 1); // New candidate. Add with 1 vote } /** * Finds the candidates with the fewest votes. * @return a list of candidates with the fewest votes. */ public ArrayList getLosers() { ArrayList loserList = new ArrayList(); int minTally = Integer.MAX_VALUE; // Bigger than any possible vote count for(String candidate : tally.keySet()) { int candidateTally = tally.get(candidate); if(candidateTally < minTally) { // Found new loser? loserList.clear(); // Forget previous losers loserList.add(candidate); // Remember new loser minTally = candidateTally; } else if(candidateTally == minTally) loserList.add(candidate); // Have another with the same low tally } return loserList; } /** * Return the election results */ public String toString() { return "Candidate names with vote tallies: \n" + tally.toString(); } }