public class WordEntity implements Comparable<WordEntity>{ @Override public int compareTo(WordEntity o) { int cmp = count.intValue() - o.count.intValue(); return (cmp == 0 ? key.compareTo(o.key) : -cmp); //Just add a negative sign here to decide whether to sort ascending or descending - cmp descending, cmp ascending //Because TreeSet will call the compareTo method of WorkForMap to determine its own sorting } private String key; private Integer count; public WordEntity ( String key,Integer count) { this.key = key; this.count = count; } public WordEntity(){ } @Override public String toString() { The number of occurrences of return key + " is: " + count; } public String getKey() { return key; } public Integer getCount() { return count; } }
import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Set; import java.util.StringTokenizer; import java.util.TreeMap; import java.util.TreeSet; public class WordCont { public void displayWordCount(String fileName){ //Character statistics try { BufferedReader reader = new BufferedReader(new FileReader(fileName)); String line = null; TreeMap<String,Integer> tm = new TreeMap<String,Integer>(); while((line=reader.readLine())!=null){ String str[] = line.split("\\s+"); for(int i = 0; i<str.length; i++){ String word = str[i].trim(); if(tm.containsKey(word)){ tm.put(word, tm.get(word)+1); }else{ tm.put(word, 1); } } } // output the string format we want System.out.println("Word=Occurrences"); Iterator iterator=tm.entrySet().iterator(); while(iterator.hasNext()) { System.out.println(" "+iterator.next()); } } catch (FileNotFoundException e) { e.printStackTrace (); }catch (IOException e) { e.printStackTrace (); } } }
import java.util.Scanner; public class Test { public static void main(String[] args) { System.out.println("ÊäÈëÎļþ·¾¶£º\n"); Scanner in=new Scanner(System.in); String line=in.nextLine(); String fileName= line.trim(); WordCont wc = new WordCont(); wc.displayWordCount(fileName); } }