Java中统计每个单词出现的次数,使用Map存储并打印出最终的Map
时间: 2023-05-28 16:05:40 浏览: 160
下面是一个例子:
```java
import java.util.HashMap;
import java.util.Map;
public class WordCount {
public static void main(String[] args) {
String text = "Hello world this is a test Hello";
String[] words = text.split("\\s+"); // 按空格分割单词
Map<String, Integer> wordCountMap = new HashMap<>();
for (String word : words) {
word = word.toLowerCase(); // 把单词转为小写
if (wordCountMap.containsKey(word)) {
wordCountMap.put(word, wordCountMap.get(word) + 1);
} else {
wordCountMap.put(word, 1);
}
}
for (Map.Entry<String, Integer> entry : wordCountMap.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
}
}
```
输出结果:
```
hello: 2
world: 1
this: 1
is: 1
a: 1
test: 1
```
阅读全文