import java.io.*; import java.util.*; import javax.swing.JFileChooser; public class FrequenciesSorted { private static class WordPair implements Comparable{ String word; int freq; public WordPair(String s, int i){ word = s; freq = i; } public int compareTo(WordPair wp){ return word.compareTo(wp.word); } } private static class WPFreq implements Comparator{ public int compare(WordPair o1, WordPair o2) { int diff = o2.freq - o1.freq; if (diff != 0) return diff; return o1.compareTo(o2); } } private static JFileChooser ourChooser = new JFileChooser(System .getProperties().getProperty("user.dir")); public static void doFreqsA(String[] words){ double start = System.currentTimeMillis(); List list = Arrays.asList(words); TreeSet unique = new TreeSet(list); WordPair[] freqs = new WordPair[unique.size()]; int index = 0; for(String s : unique){ freqs[index] = new WordPair(s,Collections.frequency(list, s)); index++; } double end = System.currentTimeMillis(); Arrays.sort(freqs, new WPFreq()); index = 0; for(WordPair s : freqs){ System.out.printf("%d\t%s\n", s.freq, s.word); 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 map = new TreeMap(); for(String s : words){ if (! map.containsKey(s)){ map.put(s, 0); } map.put(s, map.get(s)+1); } ArrayList list = new ArrayList(); /** * TODO: write code here to add every (word,count) pair * to the ArrayList list. Loop over set of keys in map and create * a new WordPair object */ //----------- code here ---------------- /** * TODO: sort the list as was done in doFreqsA, but here use * Collections.sort instead of Arrays.sort, why? Sort by * frequency of occurrences, not alphabetically by word * */ // ----------- code here ------------------- double end = System.currentTimeMillis(); int count = 0; for(WordPair wp : list){ System.out.printf("%d\t%s\n", wp.freq, wp.word); 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); } }