假设我们在Java中有一个HashMap<String, Integer>。
我如何更新(增量)字符串键的整数值为我找到的字符串的每个存在?
人们可以删除并重新输入配对,但开销将是一个问题。 另一种方法是只放一双新的,旧的就会被替换掉。
在后一种情况下,如果hashcode与我试图插入的新键发生冲突,会发生什么?哈希表的正确行为是为它分配一个不同的位置,或者在当前桶中对它进行列表。
假设我们在Java中有一个HashMap<String, Integer>。
我如何更新(增量)字符串键的整数值为我找到的字符串的每个存在?
人们可以删除并重新输入配对,但开销将是一个问题。 另一种方法是只放一双新的,旧的就会被替换掉。
在后一种情况下,如果hashcode与我试图插入的新键发生冲突,会发生什么?哈希表的正确行为是为它分配一个不同的位置,或者在当前桶中对它进行列表。
当前回答
Java 8方式:
您可以使用computeIfPresent方法并为其提供一个映射函数,该函数将被调用以基于现有值计算一个新值。
例如,
Map<String, Integer> words = new HashMap<>();
words.put("hello", 3);
words.put("world", 4);
words.computeIfPresent("hello", (k, v) -> v + 1);
System.out.println(words.get("hello"));
或者,你可以使用merge方法,其中1是默认值,函数将现有值加1:
words.merge("hello", 1, Integer::sum);
此外,还有一些其他有用的方法,如putIfAbsent、getOrDefault、forEach等。
其他回答
一句话解决方案:
map.put(key, map.containsKey(key) ? map.get(key) + 1 : 1);
散列是否存在(以0为值)或者它是否在第一个增量上“放置”到映射中?如果它是“put”在第一个增量上,代码应该是这样的:
if (hashmap.containsKey(key)) {
hashmap.put(key, hashmap.get(key)+1);
} else {
hashmap.put(key,1);
}
由于我不能评论一些答案,由于较少的声誉,我会张贴一个解决方案,我应用。
for(String key : someArray)
{
if(hashMap.containsKey(key)//will check if a particular key exist or not
{
hashMap.put(hashMap.get(key),value+1);// increment the value by 1 to an already existing key
}
else
{
hashMap.put(key,value);// make a new entry into the hashmap
}
}
Java 8方式:
您可以使用computeIfPresent方法并为其提供一个映射函数,该函数将被调用以基于现有值计算一个新值。
例如,
Map<String, Integer> words = new HashMap<>();
words.put("hello", 3);
words.put("world", 4);
words.computeIfPresent("hello", (k, v) -> v + 1);
System.out.println(words.get("hello"));
或者,你可以使用merge方法,其中1是默认值,函数将现有值加1:
words.merge("hello", 1, Integer::sum);
此外,还有一些其他有用的方法,如putIfAbsent、getOrDefault、forEach等。
使用Java8内置函数“computeIfPresent”
例子:
public class ExampleToUpdateMapValue {
public static void main(String[] args) {
Map<String,String> bookAuthors = new TreeMap<>();
bookAuthors.put("Genesis","Moses");
bookAuthors.put("Joshua","Joshua");
bookAuthors.put("Judges","Samuel");
System.out.println("---------------------Before----------------------");
bookAuthors.entrySet().stream().forEach(System.out::println);
// To update the existing value using Java 8
bookAuthors.computeIfPresent("Judges", (k,v) -> v = "Samuel/Nathan/Gad");
System.out.println("---------------------After----------------------");
bookAuthors.entrySet().stream().forEach(System.out::println);
}
}