import java.util.Set;
import java.util.HashSet;
import java.util.Map;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

public class VoterBallots
{
  private Map voteCounts;  // key is the candidate, value is the
                           // number of votes received by that candidate

  // precondition:  each entry in ballotList is a Set representing
  //                one voter's ballot
  // postcondition: voteCount.get(candidate) is the total number of
  //                times candidate appears on ballots in ballotList
  public VoterBallots(List ballotList)
  { voteCounts = new HashMap();

    Iterator itr = ballotList.iterator();
    while(itr.hasNext())
    { Set ballot = (Set)itr.next();

      Iterator itrB = ballot.iterator();
      while(itrB.hasNext())
      { String candidate = (String)itrB.next();

        if(voteCounts.containsKey(candidate))
        { Integer count = (Integer)voteCounts.get(candidate);
          voteCounts.put(candidate, new Integer(count.intValue() + 1));
        }
        else
        { voteCounts.put(candidate, new Integer(1));
        }
      }
    }
  }

  // postcondition: returns an Integer object with value equal to the
  //                maximum number of votes associated with any
  //                key in the Map voteCount
  private Integer maxVotes()
  {
    Integer max = new Integer(0);
    Iterator itr = voteCounts.keySet().iterator();
    while(itr.hasNext())
    { Integer count = (Integer)voteCounts.get(itr.next());
      if(count.compareTo(max) > 0)
        max = count;
    }
    return max;
  }

  // postcondition: returns a set containing the candidate(s)
  //                with the most votes
  public Set candidatesWithMost()
  { Integer max = maxVotes();
    Set result = new HashSet();

    Iterator itr = voteCounts.keySet().iterator();
    while(itr.hasNext())
    { String candidate = (String)itr.next();
      if(max.equals(voteCounts.get(candidate)))
        result.add(candidate);
    }
    return result;
  }

  public void listVotes()
  {
    Iterator itr = voteCounts.keySet().iterator();
    while(itr.hasNext())
    { String candidate = (String)itr.next();
      System.out.println(candidate + "\t" + voteCounts.get(candidate));
    }
  }
}
