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);
}
}
}
HashMap分拣存储1:统计每个单词出现的次数
最新推荐文章于 2026-04-26 23:46:20 发布
本文介绍如何使用HashMap来统计一段文本中每个单词出现的次数,通过这种方式进行词频分析,展示了HashMap在数据分拣和存储中的应用。

854

被折叠的 条评论
为什么被折叠?



