import java.io.*; import java.util.*; import java.util.regex.*; public class WordFreq { public static void main(String[] agrs){ compute("c:/input.in"); } public static void compute(String fn){ try{ Scanner s = new Scanner ( new File(fn)); s.useDelimiter("\\s|;|,|!|:|\\?|\\."); Map map = new TreeMap(); while(s.hasNext()){ String str = s.next().toLowerCase().trim(); if(str.equals("")) continue; if( map.get(str) == null){ map.put( str,1); }else{ int f = map.get(str); map.put(str,f+1); } } printMap(map); s.close(); }catch(Exception ex){ ex.printStackTrace(); } } public static void printMap(Map map){ Iterator iter = map.keySet().iterator(); System.out.println("Words in alphabetical order:"); Map rmap = new TreeMap(); while(iter.hasNext()){ String word = iter.next(); int freq = map.get(word); System.out.println( word + "\t" + freq); FreqRec fr = new FreqRec(word,freq); rmap.put(fr,fr); } System.out.println("Words in order of frequencies:"); Iterator iter2 = rmap.keySet().iterator(); while( iter2.hasNext()){ System.out.println(iter2.next()); } } } class FreqRec implements Comparable{ String w; int freq; public FreqRec(String w, int freq){ this.w = w; this.freq =freq; } public String toString(){ return w + "\t" + freq ; } public int compareTo(Object obj){ if(obj instanceof FreqRec){ FreqRec fr = (FreqRec) obj; int x = fr.freq - this.freq; if(x == 0) return this.w.compareTo(fr.w); return x; }else{ throw new RuntimeException ("invalid type"); } } }