(1)、新建文本文件data.txt
(2) 随便输入一些英文单词,单词之间用 “空格”隔开
(3) 统计各个单词出现的次数。
(4)对结果进行排序
a、按照次数进行降序
b、如果次数相同,安装单词的字典顺序排序
public static void main(String[] args) throws IOException { CountWord countWord = new CountWord(); FileReader fr = new FileReader("D:/bigdata/data.txt"); BufferedReader br = new BufferedReader(fr); String result =countWord.reader(br); String [] str = result.split(" ");//使用split分割单词,单词之间是使用空格隔开的 Map<String,Integer> mapWords = new HashMap<String,Integer>(); mapWords = countWord.save(str); List<Map.Entry<String, Integer>> list = countWord.wordSort(mapWords); countWord.print(list); } /* 读取字符串 */ private String reader(BufferedReader br) throws IOException { String result =""; StringBuffer buffer = new StringBuffer(); String line =br.readLine();//按行读取 while (line!= null) {//当行不为空的时候继续读取 buffer.append(line);//保存到字符串变量buffer中 buffer.append(" ");//行之间使用空格隔开 line = br.readLine();//继续读取下一行 } result = buffer.toString();//将stringbuffer转换成字符串 return result; } /* 将读取到的字符串存入到Map中 */ private Map<String,Integer> save(String [] str){ Map<String,Integer> mapWords = new HashMap<String,Integer>();//定义一个hashMap存储分割的单词和出现的次数 //遍历单词数组 for(String st : str) {//如果map当前中不包含该单词,那么将该单词加入到map集合中,该单词作为key,值设为1 if(!mapWords.containsKey(st)) { mapWords.put(st,1); }//如果map当前中包含该单词,那么取出该单词对应的值(即该单词已经出现的次数),将其加1后,保存回去。 else { Integer iCount = mapWords.get(st); iCount++; mapWords.put(st,iCount); } } return mapWords; } /* 将Map里面的字符串转换成list对其进行排序 */ private List<Map.Entry<String, Integer>> wordSort(Map mapWords){ //将map转换成list进行排序,这里使用了map的Entry方法 List<Map.Entry<String, Integer>> list = new ArrayList<Map.Entry<String, Integer>>(mapWords.entrySet()); //使用工具类 Collections来排序 Collections.sort(list, new Comparator<Map.Entry<String, Integer>>() { public int compare(Map.Entry<String, Integer> v1, Map.Entry<String, Integer> v2) {//排序函数 // return (v2.getValue() - v1.getValue()); return (v2.getValue()).compareTo(v1.getValue()); } }); return list; } /* 输出 */ private void print(List<Map.Entry<String, Integer>> list){ for(Map.Entry<String,Integer> results: list) {//遍历输出 String strKey = results.getKey();//出现的单词 Integer iCount = results.getValue();//统计次数 System.out.println(strKey+" "+"出现了"+ iCount+"次");//输出 } } }
下面是执行的结果