java hashmap案例
时间: 2023-09-24 14:13:38 浏览: 96
以下是一个使用Java HashMap的简单案例:
假设你要统计一段文本中每个单词出现的次数。你可以使用HashMap来存储每个单词和它出现的次数。具体步骤如下:
1. 将整段文本转化为单词数组。
2. 遍历单词数组,对每个单词进行如下操作:
a. 如果HashMap中不存在该单词,则将该单词作为key,对应的value设置为1。
b. 如果HashMap中已存在该单词,则将该单词对应的value加1。
3. 遍历完所有单词后,HashMap中存储的每个单词和它出现的次数就是统计结果。
下面是示例代码:
```
import java.util.HashMap;
public class WordCount {
public static void main(String[] args) {
String text = "This is a sample text with several words. We want to count the occurrences of each word.";
String[] words = text.split(" "); // 将文本转化为单词数组
HashMap<String, Integer> wordCountMap = new HashMap<>(); // 创建HashMap
// 遍历单词数组,统计每个单词出现的次数
for (String word : words) {
if (wordCountMap.containsKey(word)) { // 如果HashMap中已存在该单词,则将对应的value加1
int count = wordCountMap.get(word);
wordCountMap.put(word, count + 1);
} else { // 如果HashMap中不存在该单词,则将该单词作为key,对应的value设置为1
wordCountMap.put(word, 1);
}
}
// 输出统计结果
for (String word : wordCountMap.keySet()) {
System.out.println(word + " : " + wordCountMap.get(word));
}
}
}
```
输出结果:
```
This : 1
is : 1
a : 1
sample : 1
text : 1
with : 1
several : 1
words. : 1
We : 1
want : 1
to : 1
count : 1
the : 2
occurrences : 1
of : 1
each : 1
word. : 1
```
阅读全文
相关推荐
















