import java.util.*; import java.io.*; public class MedalCount2 { public static void main(String[] args) throws IOException { PrintStream output = System.out; Scanner input = new Scanner(System.in); Map> medals = new TreeMap>(); // read the input using a scanner final String INPUT_NAME = "medals.txt"; Scanner in = new Scanner(new File(INPUT_NAME)); while (in.hasNextLine()) { String line = in.nextLine(); if (line.isEmpty()) { continue; } String regex = ","; String[] s = line.split(regex); // constants to index into s final int EVENT = 0; final int GOLD = 1; final int SILVER = 2; final int BRONZE = 3; String event = s[EVENT]; String goldCountry = s[GOLD]; String silverCountry = s[SILVER]; String bronzeCountry = s[BRONZE]; // constants to index into the List holding the medal counts // for each country final int LIST_GOLD = 0; final int LIST_SILVER = 1; final int LIST_BRONZE = 2; // update the gold medal winning country List goldMedals = medals.get(goldCountry); if (goldMedals == null) { goldMedals = new ArrayList(); goldMedals.add(1); goldMedals.add(0); goldMedals.add(0); } else { int numGold = goldMedals.get(LIST_GOLD); goldMedals.set(0, numGold + 1); } medals.put(goldCountry, goldMedals); // update the silver medal winning country List silverMedals = medals.get(silverCountry); if (silverMedals == null) { silverMedals = new ArrayList(); silverMedals.add(0); silverMedals.add(1); silverMedals.add(0); } else { int numSilver = silverMedals.get(LIST_SILVER); silverMedals.set(1, numSilver + 1); } medals.put(silverCountry, silverMedals); // update the bronze medal winning country List bronzeMedals = medals.get(bronzeCountry); if (bronzeMedals == null) { bronzeMedals = new ArrayList(); bronzeMedals.add(0); bronzeMedals.add(0); bronzeMedals.add(1); } else { int numBronze = bronzeMedals.get(LIST_BRONZE); bronzeMedals.set(2, numBronze + 1); } medals.put(bronzeCountry, bronzeMedals); } // Gold medal counts: // Find the unique gold medal counts by putting the number // of gold medals won by each country into a TreeSet TreeSet ascendingGoldCounts = new TreeSet(); for (List countryMedalCount : medals.values()) { ascendingGoldCounts.add(countryMedalCount.get(0)); } // Reverse the set so that we get the unique gold medal counts // in descending order (from largest to smallest) Set goldCounts = ascendingGoldCounts.descendingSet(); // For each number of gold medals won (from largest to smallest) for (Integer numGold : goldCounts) { // Find the countries that won numGold for (String country : medals.keySet()) { Integer thisGold = medals.get(country).get(0); if (thisGold.equals(numGold)) { Integer thisSilver = medals.get(country).get(1); Integer thisBronze = medals.get(country).get(2); output.printf("%25s %2s %2s %2s%n", country, thisGold.toString(), thisSilver.toString(), thisBronze.toString()); } } } } }