The number of English words and sort statistics

 1 import java.io.*;
 2 import java.util.*;
 3 public class treat {
 4 
 5     public static void main(String[] args) {
 6         Map<String,Integer> map=new HashMap<String,Integer>();
 7         try {
 8             File file=new File("/Users/lilongrong/Desktop/win.txt");
 9             BufferedReader read=new BufferedReader(new FileReader(file));
10             String str;
11             while((read.readLine())!=null) {
12                 str=read.readLine();
13                 String[] strsplit=str.split("\\W+");
14                 for(int i=0;i<strsplit.length;i++) {
15                     if(map.containsKey(strsplit[i])) {
16                         int a;
17                         a=map.get(strsplit[i]);
18                         map.put(strsplit[i],a+1);
19                     }else {
20                         map.put(strsplit[i],1);
21                     }
22                 }
23             }
24             Iterator<Map.Entry<String,Integer>> iterator=map.entrySet().iterator();
25             double qwe=map.size();
26             /*while(iterator.hasNext()) {
27                 Map.Entry<String,Integer> entry=iterator.next();
28                 System.out.printf("%s:%d  %.2f\n",entry.getKey(),entry.getValue(),entry.getValue()/qwe);
29             }*/
30         }
31         catch(Exception e){
32             System.err.println(e);
33         }
34         List<Map.Entry<String,Integer>> list=new ArrayList<>(map.entrySet());
35         Collections.sort(list, new Comparator<Map.Entry<String, Integer>>(){
36             @Override
37             public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
38                 return o2.getValue().compareTo(o1.getValue());
39             }
40         });
41         for(Map.Entry<String,Integer> a:list){
42             System.out.println(a.getKey()+":"+a.getValue());
43         }
44 
45     }
46 
47 }

Sort the program achieved a number of large text word count and word appears, the specific implementation process is as follows:

1, Bufferedreader class implements text read, split, Split functions implemented in the class String word segmentation.

2, the establishment of the Map class, implement statistical functions.

3, without using the sort iterator output interfaces used when sorting List, and then use the sort function under sorting Collections, for traversal cycle output.

reward:

1, List is an interface, the ArrayList is a class oriented programming interface;

2, the read file, the file is converted to text, and then reads the text buffer;

3, template class Map <String, Integer>;

4, rewriting the override function;

5, iterator use;

6, for (:) traversal of use.

Guess you like

Origin www.cnblogs.com/jiaoaoshirenjinbu/p/11809975.html