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

统计单词出现次数,按单词出现频率的升序显示。创建一个名为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);
         }
    }
}

 



你可能感兴趣的:(java,J2SE,Collection,TreeMap)