繁体   English   中英

递增哈希图Java的值

[英]Incrementing the value of a hashmap java

我有一个地方的哈希图:

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

在这个位置,我有一个关键的位置,以及一个在文本中出现该位置的次数的值。

说我有一条短信:

  1. iloveLondon
  2. IamforLondon
  3. allaboutParis

哪些也存储在哈希图中:

 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
      }
}

在此示例中,输出应为:London,2 Paris,1 Dublin,0

除输出值并递增值以外,我已经掌握了所有建议?

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

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

如果地图不包含“伦敦”,则get将返回null,以处理这种情况,您需要执行以下操作:

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

places.put("London", value);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM