import java.io.*;
import java.util.*;

import javax.swing.JFileChooser;

public class Frequencies {
    private static JFileChooser ourChooser = new JFileChooser(System
            .getProperties().getProperty("user.dir"));

    public static void doFreqsA(String[] words){
        double start = System.currentTimeMillis();
        List<String> list = Arrays.asList(words);
        TreeSet<String> unique = new TreeSet<String>(list);
        int[] freqs = new int[unique.size()];
        int index = 0;
        for(String s : unique){
            freqs[index] = Collections.frequency(list, s);
            index++;
        }
        double end = System.currentTimeMillis();
        index = 0;
        for(String s : unique){
            System.out.printf("%d\t%s\n", freqs[index],s);
            index++;
            if (index >= 20) break;
        }
        System.out.printf("time to complete: %f\n\n",(end-start)/1000.0);
    }
    
    public static void doFreqsB(String[] words){
        double start = System.currentTimeMillis();
        TreeMap<String,Integer> map = new TreeMap<String,Integer>();
        for(String s : words){
            if (! map.containsKey(s)){
                map.put(s, 0);
            }
            map.put(s, map.get(s)+1);
        }
        double end = System.currentTimeMillis();
        int count = 0;
        for(String s : map.keySet()){
            System.out.printf("%d\t%s\n", map.get(s),s);
            count++;
            if (count >= 20) break;
        }
        System.out.printf("time to completed %f\n",(end-start)/1000.0);
    }
    
    public static void main(String[] args) throws FileNotFoundException{
        int retval = ourChooser.showOpenDialog(null);

        if (retval == JFileChooser.APPROVE_OPTION) {
            Scanner s = new Scanner(ourChooser.getSelectedFile());
            String[] words = s.useDelimiter("\\Z").next().split("\\s+");
            System.out.printf("total # words read: %d\n", words.length);
            doFreqsA(words);
            doFreqsB(words);

        }
        System.exit(0);
    }
    
}
