查找字母出现的次数
这道题的思路在后续题目中会用到。
**题目要求:**给出一个字符串数组,输出每个字符串及其出现次数。
**思路:**将数组里的字符串按顺序放入 Map 中。如果字符串未出现过,放入并计数为 1;如果已存在,则更新计数加 1。
例如输入 this, dog, cat, cat, this, dog,最终统计结果如下。
代码实现:
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
public class Test {
public static Map<String, Integer> countWords(String[] words) {
Map<String, Integer> map = new HashMap<>();
for (String word : words) {
if (map.get(word) == null) {
map.put(word, 1);
} else {
int val = map.get(word);
map.put(word, val + 1);
}
}
return map;
}
public static void main(String[] args) {
String[] words = {"this", "dog", "cat", "cat", "this", "dog"};
Map<String, Integer> map = countWords(words);
Set<Map.Entry<String, Integer>> entryset = map.entrySet();
for (Map.Entry<String, Integer> entry : entryset) {
System.out.println("Key: " + entry.getKey() + + entry.getValue());
}
}
}


