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 vote total of 1. * @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 } /** * Find 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 a possible loser? loserList.clear(); // forget the previous possible losers loserList.add(candidate); // remember the 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(); } }