我有一个地点的 HashMap :
HashMap <String, Integer> places = new HashMap <String, Integer>();
places.put("London",0);
places.put("Paris",0);
places.put("dublin",0);
在这个地方,我有一个地方的键和一个该地方在文本中出现的次数的值。
假设我有一条短信:
我爱伦敦
Iamfor伦敦
所有关于巴黎
也存储在 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/