假设我们在Java中有一个HashMap<String, Integer>。
我如何更新(增量)字符串键的整数值为我找到的字符串的每个存在?
人们可以删除并重新输入配对,但开销将是一个问题。 另一种方法是只放一双新的,旧的就会被替换掉。
在后一种情况下,如果hashcode与我试图插入的新键发生冲突,会发生什么?哈希表的正确行为是为它分配一个不同的位置,或者在当前桶中对它进行列表。
假设我们在Java中有一个HashMap<String, Integer>。
我如何更新(增量)字符串键的整数值为我找到的字符串的每个存在?
人们可以删除并重新输入配对,但开销将是一个问题。 另一种方法是只放一双新的,旧的就会被替换掉。
在后一种情况下,如果hashcode与我试图插入的新键发生冲突,会发生什么?哈希表的正确行为是为它分配一个不同的位置,或者在当前桶中对它进行列表。
当前回答
使用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);
}
}
其他回答
hashmap.put(key, hashmap.get(key) + 1);
put方法将替换现有键的值,如果不存在则创建该键。
@Matthew的解决方案是最简单的,在大多数情况下都会表现得很好。
如果你需要高性能,AtomicInteger是一个比@BalusC更好的解决方案。
然而,一个更快的解决方案(如果线程安全不是一个问题)是使用TObjectIntHashMap,它提供了一个增量(键)方法,使用原语和比创建AtomicIntegers更少的对象。如。
TObjectIntHashMap<String> map = new TObjectIntHashMap<String>()
map.increment("aaa");
没有NullPointerException的更干净的解决方案是:
map.replace(key, map.get(key) + 1);
使用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);
}
}
map.put(key, map.get(key) + 1);
应该没问题。它将更新现有映射的值。注意,这使用了自动装箱。在map.get(key)的帮助下,我们得到相应的key值,然后您可以根据您的需求进行更新。在这里,我正在更新,使value增加1。