统计文章中单词的字数并按照出现的频率排序(treeSet)

基本思路:用hashmap存储key值为单词,value为单词出现的频率。

  1. hashmap存储对单词的遍历
  2. map的遍历存储在set中
  3. 排序 TreeSet
  4. 对wordEntity实现comparable接口重写compareTo()和toString()
  5. 增序为cmp的值,降序课为-cmp的值
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.TreeSet;


public class wordCen {
    public static void main(String args[]){
        System.out.println("请输入文件的地址");
        Scanner in=new Scanner(System.in);
        String Filepath=in.next();
        File file=new File(Filepath);
        String buffer;
        Map map=new HashMap();
        try {
            BufferedReader reader=new BufferedReader(new FileReader(file));
             while((buffer=reader.readLine())!=null){
             StringTokenizer st = new StringTokenizer(buffer, ", !’");
             while(st.hasMoreTokens()){
                 String str=st.nextToken();
                 if(map.containsKey(str)) map.put(str, map.get(str)+1);
                 else map.put(str, 1);
             }
             }

             Set set=new TreeSet();
             for(String s:map.keySet()){
                 WordEntity wordEntry=new WordEntity(s,map.get(s));
                 set.add(wordEntry);     
             }

             Iterator  ite=set.iterator();
             int count=0;
             while(ite.hasNext()){
                // String wr=ite.next();
                 if(count>=10) break;
                 System.out.println(ite.next());
                 count++;

             }
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            System.out.println("文件没有找到");
        }
        catch(IOException e){
            System.out.println("文件读异常");    
        }

    }
}

wordEntity类的实现:


public class WordEntity implements Comparable{
private String word;
private Integer count;
public WordEntity(String key, Integer value) {
    super();
    this.word = key;
    this.count = value;
}
public String getKey() {
    return word;
}
public Integer getValue() {
    return count;
}
public void setKey(String key) {
    this.word = key;
}
public void setValue(Integer value) {
    this.count = value;
}
@Override
public String toString() {
    return "WordEntity key=" + word + ", 出现的次数" + count ;
}
@Override
public int compareTo(WordEntity O) {
    // TODO Auto-generated method stub
    int cmp=count.intValue()-O.count.intValue();
    return (cmp==0?word.compareTo(O.getKey()):-cmp);
}

}

你可能感兴趣的:(算法-数据结构)