单机wordcount

 1 package com.util;
 2 
 3 import java.io.BufferedReader;
 4 import java.io.File;
 5 import java.io.FileInputStream;
 6 import java.io.InputStreamReader;
 7 import java.util.*;
 8 
 9 /**
10  * Created by jinxin11 on 2017/2/6.
11  */
12 public class WordCount {
13 
14     //排序方法
15     public static <K, V extends Comparable<V>> TreeMap<K, V> sortByValues(
16             final Map<K, V> map) {
17         Comparator<K> valueComparator = new Comparator<K>() {
18             public int compare(K k1, K k2) {
19                 int compare = map.get(k2).compareTo(map.get(k1));
20                 if (compare == 0)
21                     return 1;
22                 else
23                     return compare;
24             }
25         };
26         TreeMap<K, V> sortedByValues = new TreeMap<K, V>(valueComparator);
27         sortedByValues.putAll(map);
28         return sortedByValues;
29     }
30 
31     public static void main(String[] args) {
32         try {
33             Map<String,Integer> map = new HashMap();
34             //读取文件
35             File file = new File("C:\\Users\\jinxin11\\Desktop\\wordcount.txt");
36             if (file.isFile() && file.exists()) {
37                 InputStreamReader read = new InputStreamReader(new FileInputStream(file));
38                 BufferedReader bufferedReader = new BufferedReader(read);
39                 String lineTXT = null;
40                 while ((lineTXT = bufferedReader.readLine()) != null) {
41                     //以空格切割每行数据
42                     String[] lines = lineTXT.split(" ");
43                     //将单词和单词计数放入map
44                     for (String str : lines) {
45                         if (map.containsKey(str)) {
46                             map.put(str, map.get(str) + 1);
47                         } else {
48                             map.put(str, 1);
49                         }
50                     }
51                 }
52                 read.close();
53                 //对map进行排序
54                 TreeMap<String, Integer> treeMap = sortByValues(map);
55                 System.out.println(treeMap);
56                 System.out.println(treeMap.firstKey());
57             }else{
58                 System.out.println("找不到指定的文件!");
59                 }
60             } catch (Exception e) {
61                 System.out.println("读取文件内容操作出错");
62                 e.printStackTrace();
63             }
64          }
65 }

 

posted on 2017-02-08 18:20  聂政didi  阅读(250)  评论(0编辑  收藏  举报

导航