Java 给定哈希图中的键,如何更新值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4157972/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to update a value, given a key in a hashmap?
提问by laertis
Suppose we have a HashMap<String, Integer>
in Java.
假设我们HashMap<String, Integer>
在 Java 中有一个。
How do I update (increment) the integer-value of the string-key for each existence of the string I find?
如何为我找到的每个存在的字符串更新(增加)字符串键的整数值?
One could remove and reenter the pair, but overhead would be a concern.
Another way would be to just put the new pair and the old one would be replaced.
可以移除并重新进入这对,但开销将是一个问题。
另一种方法是只放置一对新的,旧的将被替换。
In the latter case, what happens if there is a hashcode collision with a new key I am trying to insert? The correct behavior for a hashtable would be to assign a different place for it, or make a list out of it in the current bucket.
在后一种情况下,如果哈希码与我尝试插入的新密钥发生冲突,会发生什么情况?哈希表的正确行为是为它分配一个不同的位置,或者在当前存储桶中创建一个列表。
采纳答案by Matthew Flaschen
map.put(key, map.get(key) + 1);
should be fine. It will update the value for the existing mapping. Note that this uses auto-boxing.
应该没事。它将更新现有映射的值。请注意,这使用了自动装箱。
回答by BalusC
Replace Integer
by AtomicInteger
and call one of the incrementAndGet
/getAndIncrement
methods on it.
替换Integer
为AtomicInteger
并调用其上的incrementAndGet
/getAndIncrement
方法之一。
An alternative is to wrap an int
in your own MutableInteger
class which has an increment()
method, you only have a threadsafety concern to solve yet.
另一种方法是将 an 包装int
在您自己的MutableInteger
具有increment()
方法的类中,您只需要解决线程安全问题。
回答by Peter Lawrey
@Matthew's solution is the simplest and will perform well enough in most cases.
@Matthew 的解决方案是最简单的,并且在大多数情况下都能很好地执行。
If you need high performance, AtomicInteger is a better solution ala @BalusC.
如果您需要高性能,AtomicInteger 是更好的解决方案 ala @BalusC。
However, a faster solution (provided thread safety is not an issue) is to use TObjectIntHashMapwhich provides a increment(key) method and uses primitives and less objects than creating AtomicIntegers. e.g.
然而,一个更快的解决方案(假设线程安全不是问题)是使用TObjectIntHashMap,它提供了一个 increment(key) 方法并使用原语和比创建 AtomicIntegers 更少的对象。例如
TObjectIntHashMap<String> map = new TObjectIntHashMap<String>()
map.increment("aaa");
回答by oracleruiz
hashmap.put(key, hashmap.get(key) + 1);
The method put
will replacethe value of an existing key and will create it if doesn't exist.
该方法put
将替换现有键的值,如果不存在则创建它。
回答by VanHoutte
Use a for
loop to increment the index:
使用for
循环来增加索引:
for (int i =0; i<5; i++){
HashMap<String, Integer> map = new HashMap<String, Integer>();
map.put("beer", 100);
int beer = map.get("beer")+i;
System.out.println("beer " + beer);
System.out ....
}
回答by NARAYANAN.M
Try:
尝试:
HashMap hm=new HashMap<String ,Double >();
NOTE:
笔记:
String->give the new value; //THIS IS THE KEY
else
Double->pass new value; //THIS IS THE VALUE
You can change either the key or the value in your hashmap, but you can't change both at the same time.
您可以更改哈希图中的键或值,但不能同时更改两者。
回答by isuru
You can increment like below but you need to check for existence so that a NullPointerException is not thrown
您可以像下面这样递增,但您需要检查是否存在,以便不会抛出 NullPointerException
if(!map.containsKey(key)) {
p.put(key,1);
}
else {
p.put(key, map.getKey()+1);
}
回答by sudoBen
Does the hash exist (with 0 as the value) or is it "put" to the map on the first increment? If it is "put" on the first increment, the code should look like:
散列是否存在(以 0 作为值)或者它是在第一个增量上“放置”到地图上吗?如果它在第一个增量上“放置”,则代码应如下所示:
if (hashmap.containsKey(key)) {
hashmap.put(key, hashmap.get(key)+1);
} else {
hashmap.put(key,1);
}
回答by user1048218
There are misleading answers to this question here that imply Hashtable put method will replace the existing value if the key exists, this is not true for Hashtable but rather for HashMap. See Javadoc for HashMap http://docs.oracle.com/javase/7/docs/api/java/util/HashMap.html#put%28K,%20V%29
此处对这个问题有误导性答案,暗示如果键存在,Hashtable put 方法将替换现有值,这对于 Hashtable 而言并非如此,而是对于 HashMap 而言。请参阅 HashMap 的 Javadoc http://docs.oracle.com/javase/7/docs/api/java/util/HashMap.html#put%28K,%20V%29
回答by damluar
Java 8 way:
Java 8 方式:
You can use computeIfPresent
method and supply it a mapping function, which will be called to compute a new value based on existing one.
您可以使用computeIfPresent
method 并为其提供一个映射函数,该函数将被调用以根据现有值计算新值。
For example,
例如,
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"));
Alternatevely, you could use merge
method, where 1 is the default value and function increments existing value by 1:
或者,您可以使用merge
方法,其中 1 是默认值,函数将现有值增加 1:
words.merge("hello", 1, Integer::sum);
In addition, there is a bunch of other useful methods, such as putIfAbsent
, getOrDefault
, forEach
, etc.
此外,有一堆其他有用的方法,例如putIfAbsent
,getOrDefault
,forEach
等。