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

java按单词出现次数统计单词

2014-04-12 14:48 423 查看
统计单词出现次数,按单词出现频率的升序显示。创建一个名为WordOccurrence的类实现Comparable接口。使用compareTo比较单词出现的次数。

import java.util.*;

public class WordOccurrence implements Comparable<WordOccurrence> {
private String word;
private int count;

public WordOccurrence(String word,int count) {
this.word = word;
this.count = count;
}
public int compareTo(WordOccurrence o) {
return count-o.count;
}
public boolean equals(WordOccurrence o) {
return word.equals(o.word);
}
public String toString() {
return word + " " + count;
}
}

import java.util.*;

public class Exercise22_8 {
public static void main(String[] args) {
String text = "Have a good day. Have a good class.Have a good visit. Have fun!";
String[] words = text.split("[ \n\t\r.,;:!?(){]");
TreeMap<String,Integer> treeMap = new TreeMap<String,Integer>();
for(int i=0;i<words.length;i++) {
String word = words[i].toLowerCase();
if(word.length()>0) {
if(treeMap.get(word)==null) {
treeMap.put(word,1);
}
else {
int value = treeMap.get(word);
treeMap.put(word,++value);
}
}
}
System.out.println(treeMap);
ArrayList<WordOccurrence> list = new ArrayList<WordOccurrence>();
Set<String> set = treeMap.keySet();
Iterator<String> iterator = set.iterator();
while(iterator.hasNext()) {
String n = iterator.next();
list.add(new WordOccurrence(n,treeMap.get(n)));
}
Collections.sort(list);
for(WordOccurrence element:list) {
System.out.println(element);
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: