统计文档中单词出现的频率
文档中的单词假设已经遍历读取到一个字符串数组里面
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class StrOrder {
public static void main(String[] args) {
String[] strs = { "123", "123", "12", "234", "234", "234", "3456",
"3456", "123", "12", "12", "12", "12", "12", "orar", "orar",
"orar", "orar", "show", "show", "234", "12", "show", "123",
"12", "12", "123", "12", "234", "234", "12", "12", "123",
"show", "orar", "12", "123", };
reOrder(strs);
}
private static void reOrder(String[] strs) {
// 打开一个哈希表
HashMap<String, Integer> has = new HashMap<String, Integer>();
for (int i = 0; i < strs.length; i++) {
// 若尚无此单词
if (!has.containsKey(strs[i])) {
has.put(strs[i], 1);
// 如果有,就在将次数加1
} else {
has.put(strs[i], has.get(strs[i]) + 1);
}
}
List<Map.Entry<String, Integer>> infoIds = new ArrayList<Map.Entry<String, Integer>>(has.entrySet());
// List infoIds = new ArrayList(has.entrySet());
// System.out.println(has.entrySet());
// Iterator it = has.entrySet().iterator();
// while (it.hasNext()) {
// System.out.println(it.next());
// }
// 排序前
for (int i = 0; i < infoIds.size(); i++) {
String id = infoIds.get(i).toString();
System.out.println(id);
}
// 排序
Collections.sort(infoIds, new Comparator<Map.Entry<String, Integer>>() {
public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
return (o2.getValue() - o1.getValue());
}
});
System.out.println("排序后");
for (int i = 0; i < infoIds.size(); i++) {
String id = infoIds.get(i).toString();
System.out.println(id);
}
}
}