仅供参考,勿要模仿
import java.io.BufferedReader; import java.io.FileReader; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Map; import java.util.TreeMap; import java.util.regex.Matcher; import java.util.regex.Pattern; public class WordsCounter { public static void main(String[] args) throws Exception { BufferedReader reader = new BufferedReader(new FileReader( "main.txt")); StringBuffer buffer = new StringBuffer(); String line = null; while ((line = reader.readLine()) != null) { buffer.append(line); } reader.close(); Pattern expression = Pattern.compile("[a-zA-Z]+");// 定义正则表达式匹配单词 String string = buffer.toString(); Matcher matcher = expression.matcher(string);// Map<String, Integer> map = new TreeMap<String, Integer>(); String word = ""; int times = 0; // 是否匹配单词 while (matcher.find()) { // 得到一个单词-树映射的键 word = matcher.group(); // 如果包含该键,单词出现过 if (map.containsKey(word)) { // 得到单词出现的次数 times = map.get(word); map.put(word, times + 1); } else { // 否则单词第一次出现,添加到映射中 map.put(word, 1); } } /* * 排序 */ List<Map.Entry<String, Integer>> list = new ArrayList<Map.Entry<String, Integer>>( map.entrySet()); /* * 定义排序规则,按照Entry的Value排序 */ Comparator<Map.Entry<String, Integer>> comparator = new Comparator<Map.Entry<String, Integer>>() { public int compare(Map.Entry<String, Integer> left, Map.Entry<String, Integer> right) { return (left.getValue()).compareTo(right.getValue()); } }; // 利用Collections类的sort方法来排序,按照自定义的规则排序 Collections.sort(list, comparator); // 打印最多五个 int last = list.size() - 1; for (int i = last; i > last - 5; i--) { String key = list.get(i).getKey(); Integer value = list.get(i).getValue(); System.out.println(key + " :" + value); } } }