-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWordCount.java
More file actions
64 lines (46 loc) · 1.92 KB
/
WordCount.java
File metadata and controls
64 lines (46 loc) · 1.92 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
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.Map.Entry;
import java.util.TreeMap;
public class WordCount {
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new FileReader("text.txt"));
List<String> lists = new ArrayList<String>();
String readLine = null;
while((readLine = br.readLine()) != null){
String[] wordsArr1 = readLine.split("[^a-zA-Z]");
for (String word : wordsArr1) {
if(word.length() != 0){
lists.add(word);
}
}
}
br.close();
Map<String, Integer> wordsCount = new TreeMap<String,Integer>();
for (String li : lists) {
if(wordsCount.get(li) != null){
wordsCount.put(li,wordsCount.get(li) + 1);
}else{
wordsCount.put(li,1);
}
}
SortMap(wordsCount);
}
public static void SortMap(Map<String,Integer> oldmap){
ArrayList<Map.Entry<String,Integer>> list = new ArrayList<Map.Entry<String,Integer>>(oldmap.entrySet());
Collections.sort(list,new Comparator<Map.Entry<String,Integer>>(){
@Override
public int compare(Entry<String, Integer> o1, Entry<String, Integer> o2) {
return o2.getValue() - o1.getValue();
}
});
for(int i = 0; i<list.size(); i++){
System.out.println(list.get(i).getKey()+ ": " +list.get(i).getValue());
}
}
}