您的位置:首页 > 编程语言 > Java开发

Java实现 统计单词出现的次数并按照单词频率从高到低输出

2016-06-05 16:26 826 查看
import java.util.*;

import java.util.Map.Entry;

public class CountWord {
public static void sort(Map<String,Integer> map)
{
List<Entry<String, Integer>> list=new ArrayList<Entry<String,Integer>>();
for (Entry<String, Integer> entry : map.entrySet()) {
list.add(entry);
}
Collections.sort(list,new EntryComparator());
for (Entry<String, Integer> obj : list) {
System.out.println(obj.getKey() + "\t" + obj.getValue());
}
}
public static void StatList(String str)
{
HashMap<String, Integer> map=new HashMap<>();
String []slist=str.split("\\W+");//作用:删除标点字符,\W意思是非单词字符;
for(int i=0;i<slist.length;i++)
{

// if (!map.containsKey(slist[i])) {

// map.put(slist[i], 1);

// }else{

// map.put(slist[i],map.get(slist[i])+1);

// }

Integer fre=map.get(slist[i]);
map.put(slist[i], fre==null ? 1:fre+1);
}
sort(map);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc=new Scanner(System.in);

while(sc.hasNextLine())
{
String str=sc.nextLine();
StatList(str);
}
//String string="Hello,welcome to trend!to Hello to";
sc.close();
}

}

class EntryComparator implements Comparator<Entry<String, Integer>> {
public int compare(Entry<String, Integer> o1, Entry<String, Integer> o2) {
return o2.getValue() - o1.getValue();
}

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: