package ThreadProcess;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.*;
/*
* 词频统计:获取排名前3的单词.
* */
public class test_2
{
public static void main(String[] args) throws Exception
{
BufferedReader fr = new BufferedReader(new FileReader("D:\\maven_project\\ThreadProcess\\src\\main\\java\\ThreadProcess\\test_jstakc"));
HashMap<String,Integer> hashMap = new HashMap<String,Integer>();
String line = null;
line = fr.readLine(); //先拿到第一个行.
while (line != null)
{
String[] splited = line.split(" ",-1);
for(String word:splited)
{
//没有元素直接放进去.
if (hashMap.get(word.trim()) == null)
{
hashMap.put(word.trim(),1);
}else {
int cnt = hashMap.get(word.trim());
hashMap.put(word.trim(),cnt+1);
}
}
line = fr.readLine(); //然后在继续进行读写.
}
//最终借助的是ArrayList进行排序.
ArrayList<Map.Entry<String,Integer>> arr2 = new ArrayList<Map.Entry<String,Integer>>(hashMap.entrySet());
Collections.sort(arr2, new Comparator<Map.Entry<String, Integer>>()
{
@Override
public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2)
{
return o2.getValue() - o1.getValue();
}
});
int num = 1;
for(Map.Entry<String,Integer> entry:arr2)
{
if (num > 3)
{
return ;
}
System.out.println(entry);
num += 1;
}
}
}
词频统计:获取排名前3的单词.
最新推荐文章于 2023-12-12 15:24:53 发布