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) {
String str =
"this is a cat and that is a mice and where is the food";
String[] arr = str.split(
" ");
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);
}
}
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);
}
}
}
转载请注明原文地址: https://ju.6miu.com/read-965411.html