07 Apr 2012 [ 201 week12 ]

We reviewed the Java Collections Framework, making use of this example.

This example shows a lot of the new concepts we covered, especially use of the Map interface, and its HashMap implementation:

package org.ilzd.nfl2011;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;

/**
 * Print win-loss record for each team, in order from best to worst.
 *
 */
public class WinLoss
{
    /**
    *  Simple class to store wins and losses info.
    */
    public static class WinInfo {
        public int wins = 0;
        public int losses = 0;
    }
    
    /**
    * Comparator that orders based on winning percentage.
    */
    public static class EntryCompare 
        implements Comparator<Map.Entry<String, WinInfo>> {

        public double winPercent(int win, int loss) {
            return (double)win / (win + loss);
        }
        
        // Order based on win percentage
        public int compare(Map.Entry<String, WinInfo> t, 
                Map.Entry<String, WinInfo> t1) {
            // Return -1 if t comes before t1, 1 if after, 0 if same.
            int win = t.getValue().wins;
            int loss = t.getValue().losses;
            int win1 = t1.getValue().wins;
            int loss1 = t1.getValue().losses;
            double percent = winPercent(win, loss);
            double percent1 = winPercent(win1, loss1);
            if (percent > percent1)
                return -1;
            else if (percent < percent1)
                return 1;
            else 
                return 0;
        }
    }
    
    public static void main( String[] args ) throws IOException
    {
        // Data has header:
        // Week,Day,Date,Winner,Loser,PtsW,PtsL,YdsW,TOW,YdsL,TOL
        InputStream data = WinLoss.class.getResourceAsStream("nfl-2011.csv");
        SimpleCSV csv = new SimpleCSV(data);

        // Map of team name to win/loss record.
        HashMap<String, WinInfo> teamRecords = new HashMap<String, WinInfo>();
        
        // Process all records in CSV file, keeping track of wins and losses.
        for (Map<String, String> record : csv) {
            String winner = record.get("Winner");
            // Insert a new entry for the team if the key is not present.
            if (!teamRecords.containsKey(winner))
                teamRecords.put(winner, new WinInfo());
            teamRecords.get(winner).wins++;

            String loser = record.get("Loser");
            // Insert a new entry for the team if the key is not present.
            if (!teamRecords.containsKey(loser))
                teamRecords.put(loser, new WinInfo());
            teamRecords.get(loser).losses++;
        }
        
        // To sort the teams, copy them to an array.
        ArrayList<Map.Entry<String, WinInfo>> teamArray
                = new ArrayList<Map.Entry<String, WinInfo>>(
                        teamRecords.entrySet());
        
        // Sort using our custom Comparator.
        Collections.sort(teamArray, new EntryCompare());
                
        // Print the sorted entries.
        for (Map.Entry<String, WinInfo> entry : teamArray) {
            System.out.printf("%s: %d-%d\n", entry.getKey(),
                              entry.getValue().wins, entry.getValue().losses);
        }
    }
}

Readings

Read the "Collections" chapter in the book (Chapter 12 in my copy). That chapter. contains some examples of how some of the collection classes could be implemented.