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

来源:互联网 发布:一维数组的定义方文字 编辑:程序博客网 时间:2024/05/03 08:20
统计单词出现次数,按单词出现频率的升序显示。创建一个名为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);         }    }} 



0 0