import java.io.*; import java.util.*; public class HomeworkEight { public static void main(String[] args) throws FileNotFoundException { Scanner votes = new Scanner( new File(args[0]) ); Map results = new HashMap(); // run through the file and add the candidates and votes to the results HashMap while (votes.hasNextLine()) { Scanner line = new Scanner(votes.nextLine()); String name = line.next(); int rating = line.nextInt(); // if the candidate is already in the map, add the rating to that value // if not, first add the candidate to the map, then add the rating if (results.containsKey(name)) { results.get(name).add(rating); } else { results.put(name, new Candidate(name)); results.get(name).add(rating); } } // create a new ArrayList to be sorted and populate it with values from the results // hashmap. The values in that map are of the Candidate class ArrayList candidates = new ArrayList(); for (String name : results.keySet()) candidates.add(results.get(name)); // sort by number of votes in descending order. Collections.sort() with // one argument uses the compare criteria inside the class type of the // ArrayList being sorted. Collections.sort(candidates); System.out.println("Order by number of votes cast:" + candidates); // sort by average vote. Collections.sort() has two arguments here, the first // is the ArrayList of candidates, the second is a Comparator class which compares // the candidates using other criteria specified in the Judge class Collections.sort(candidates, new Judge()); System.out.println("Order by average value of votes cast: " + candidates); } }