用Java统计单词出现的次数

普通方法

package collection03;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

/***
 * 分拣存储  1:N
 * 统计单词出现的次数
 * @author zw
 *
 */
public class MapDemo02 {
    public static void main(String[] args){
        String[] arr ="I love you not for who you are, but for who I am before you".split(" ");
        Map<String,Integer> map = new HashMap<String,Integer>(); 
        for(String key:arr){
            //System.out.println(key);//查看每个单词
            if(!map.containsKey(key)){
                map.put(key, 1);
            }else{//不存在
                map.put(key, map.get(key)+1);           }
            }

        Set<String> keySet = map.keySet();//获取对象
        Iterator<String> ter =keySet.iterator();
        while(ter.hasNext()){
            String key = ter.next();
            Integer value = map.get(key);
            System.out.println(key+"出现了"+value+"次");
        }

    }

}





利用JavaBean做

package collection03;

public class Words {
    private String word;
    private int counts;
    public Words(String word) {
        super();
        this.word =word;
    }

    public Words(){

    }
    public Words(String word, int counts) {
        super();
        this.word = word;
        this.counts = counts;
    }
    public String getWord() {
        return word;
    }
    public void setWord(String word) {
        this.word = word;
    }
    public int getCounts() {
        return counts;
    }
    public void setCounts(int counts) {
        this.counts = counts;
    }

}
package collection03;

import java.util.HashMap;
import java.util.Map;

/***
 * 分拣存储  1:N
 * 统计单词出现的次数
 * @author zw
 *
 */
public class MapDemo01 {
    public static void main(String[] args){
        String[] arr ="I love you not for who you are, but for who I am before you".split(" ");
        Map<String,Words> map = new HashMap<String,Words>(); 
        for(String key:arr){

            if(!map.containsKey(key)){
                map.put(key, new Words(key));
                }

            Words value = map.get(key);
            value.setCounts(value.getCounts()+1);
            }
        for(String key:map.keySet()){
            Words value = map.get(key);
            System.out.println(key+"出现了"+value.getCounts()+"次");
    }
}
}

111

  • 3
    点赞
  • 24
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值