java - 增加 hashmap java 的值

标签 java hashmap

我有一个地点的 HashMap :

HashMap <String, Integer> places = new HashMap <String, Integer>();
places.put("London",0);
places.put("Paris",0);
places.put("dublin",0);

在这个地方,我有一个地方的键和一个该地方在文本中出现的次数的值。

假设我有一条短信:

  1. 我爱伦敦
  2. Iamfor伦敦
  3. 所有关于巴黎

也存储在 HashMap 中:

 HashMap <String, Integer> text = new HashMap <String, Integer>();

我有一个条件语句来检查该位置是否在文本中(其中大写和小写被忽略:

for (String p: places):
{
   for(String t : text):
      if t.tolowercase().contains(p.tolowercase())
      {
        //then i would like to increment the value for places of the places hashmap
      }
}

在此示例中,输出应为: 伦敦, 2 巴黎, 1 都柏林, 0

除了输出值和递增它之外,我已经得到了一切,有什么建议吗?

最佳答案

要增加一个值,您需要做的是:

places.put("London",places.get("London")+1);

如果 map 不包含“London”,那么 get 将返回 null,要处理这种情况,您需要执行以下操作:

Integer value = places.get("London");
if (value == null) {
   value = 1;
} else {
   value += 1;
}

places.put("London", value);

关于java - 增加 hashmap java 的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22000665/

相关文章:

java - 输入清理以不破坏 JSON 语法

list - Scala HashMap列表: simpler default?

java - HashMap.remove 和垃圾回收

java - 本例对HashMap哈希算法的解释

java - 为什么我的计数器在每次循环执行代码后没有增加?

java - 如何在不创建新的 Java Swing 的情况下 setText

java - leetcode 108 将排序数组转换为二叉搜索树

java - 我如何防止在 Seam 中重新提交表单?

java - 为什么 Hashmap 允许空键?

java - java 中的 map 和自定义对象