1.使用containsKey()
Map<String, Integer> map = new HashMap<>();
for (String word : words) {
if (map.containsKey(word)) {
map.put(word, map.get(word) + 1);
}
else {
map.put(word, 1);
}
}
2.使用get() / getOrDefault()
```java
if (map.get(word) == null) {
map.put(word, 1);
}
else {
map.put(word, count + 1);
}
map.put(word, map.getOrDefault(word, 0) + 1);
3.AtomicInteger / 自定义可变 int 封装类
Map<String, AtomicInteger> map = new HashMap<>();
AtomicInteger count = map.get(word);
if (count == null) {
map.put(word, new AtomicInteger(1));
}
else {
count.incrementAndGet();
}