HashMap分拣存储1:统计每个单词出现的次数

本文介绍如何使用HashMap来统计一段文本中每个单词出现的次数,通过这种方式进行词频分析,展示了HashMap在数据分拣和存储中的应用。
public class Sorting {
    /**
     * 统计每个单词出现的次数 this is a cat and that is a mice and where is the food?
     * HashMap分拣存储 思想:实现1:N 一对多(一个键多个值) 分组:一个键一个容器
     * 
     * 1、分割字符串(按照空格来切割) 2、分拣存储 3、按要求查看 单词出现的次数
     */
    public static void main(String[] args) {
        // 1、分割字符串(按照空格来切割)
        String str = "this is a cat and that is a mice and where is the food";
        String[] arr = str.split(" ");
        // 2、分拣存储
        Map<String, Integer> map = new HashMap<String, Integer>();
        for (String key : arr) {
            // 查看是否存在该单词
            if (!map.containsKey(key)) { // 不存在
                map.put(key, 1);
            } else {
                map.put(key, map.get(key) + 1);
            }
            //另一种存储方式
//          Integer value = map.get(key);
//          if(value == null){
//              map.put(key, 1);
//          }else{
//              map.put(key, value + 1);
//          }
        }
        // 3、按要求查看 单词出现的次数
        Set<String> keySet = map.keySet();
        // 获取对象
        Iterator<String> it = keySet.iterator();
        while (it.hasNext()) {
            String key = it.next();
            Integer value = map.get(key);
            System.out.println(key + "-->" + value);
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值