要求:統計文本中出現的單詞數,並按數量降序、單詞升序輸出
在一個名爲word.txt中放入
after a minute or two and said to his friend he opened them again
a minute or two and said to
friend he opened them again
and closed and to his
源代碼
public static void main(String[] args) throws IOException {
StringBuffer sb = readFile(); //讀取文本文件中的內容
Map<String,Integer> map = getWord(sb); //取出單詞和單詞出現的次數存入map中
List<Map.Entry<String,Integer>> list = sortValue(map); //根據value對map進行排序
for(Map.Entry<String,Integer> entry:list){
System.out.println(entry.getKey()+":"+entry.getValue());
}
}
/**
* 根據map的value對map進行排序
* @param map key:單詞;value:出現的次數
* @return 按倒敘方式排好序的list
*/
private static List<Map.Entry<String, Integer>> sortValue(Map<String, Integer> map) {
List<Map.Entry<String,Integer>> list = new ArrayList<>(map.entrySet());
/**
* Comparator(接口)是匿名內部類,compare是創建匿名內部類要實現的抽象方法
* Comparator可看作一個排序器
*/
Collections.sort(list, new Comparator<Map.Entry<String, Integer>>() {
/**
* 對list進行排序;o1和o2誰在compareTo之前,誰就從list第一位開始取,在compateTo之後的從第二位開始取
* 當o2小於o1時(也就是返回值爲-1時),交換o2和o1的位置
* @param o1 list從第二位開始取
* @param o2 list從第一位開始取
* @return 返回0和1時位置不變,返回-1時交換當前o1和o2的位置
*/
@Override
public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
return o2.getValue().compareTo(o1.getValue()); //compareTo是Comparable接口的的方法,返回值爲1,0,-1
}
});
return list;
}
/**
* 將StringBuffer中的單詞單個取出存入map中,單詞作爲key,出現的次數作爲value
* @param sb 文本中取出來的內容
* @return 將內容中的單詞作爲key,出現次數作爲value存好的map
*/
private static Map<String, Integer> getWord(StringBuffer sb) {
Map<String,Integer> map = new TreeMap<>();//用TreeMap,存入後key就是有序的
StringBuffer word = new StringBuffer();
/*String word = String.valueOf(new StringBuffer());
String[] str = word.split(" "); //使用split將字符串分隔," "分隔條件爲空格*/
for (int i=0;i<sb.length();i++){
char c = sb.charAt(i);
if(c != ' '){
word.append(c);
}else {
String str = word.toString();
if(map.containsKey(str)){
Integer value = map.get(str);
map.put(str,++value);
}else {
Integer value = 1;
map.put(str,value);
}
word = new StringBuffer();
}
}
return map;
}
/**
* 從文件中讀內容,存入StringBuffer
* @return 存好內容的StringBuffer
* @throws IOException
*/
private static StringBuffer readFile() throws IOException {
FileReader fis = new FileReader("E:/Code/wordCount/word.txt");
BufferedReader br = new BufferedReader(fis);
StringBuffer sb = new StringBuffer();
String it = br.readLine();
while (it != null){
sb.append(it);
sb.append(" ");
it = br.readLine();
}
return sb;
}
運行結果