利用TreeMap集合类,其中按照entry.value排列需要考虑一下具体思路,最后结合lameda表达式完成排列
import java.io.*;
import java.util.*;
/**
* Created by changqing on 2017/3/18.
*/
public class CountWords{
public static void main(String[] args) throws IOException {
File file = new File("test.txt");
BufferedReader bf = new BufferedReader(new FileReader(file));
String line;
String reg = "\\s+";
TreeMap<String, Integer> tm = new TreeMap<>();
while ((line = bf.readLine()) != null) {
String[] strs = line.split(reg);
for (String str : strs) {
if(!tm.containsKey(str))
tm.put(str,1);
tm.put(str,tm.get(str)+1);
}
}
List<Map.Entry<String, Integer>> list = new ArrayList<Map.Entry<String, Integer>>(tm.entrySet());
Collections.sort(list, (a, b) -> b.getValue() - a.getValue());
list.forEach(it -> System.out.println(it.getKey()+" "+it.getValue()));
}
}