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

22 篇文章 0 订阅
2 篇文章 0 订阅
统计单词出现次数,按单词出现频率的升序显示。创建一个名为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
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值