Java 在 HashMap 中增加一个整数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4277388/
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
Increment an Integer within a HashMap
提问by NimChimpsky
Do I have to return the object and then put a new one in ? Or can I just directly increment ?
我是否必须返回对象然后放入一个新对象?或者我可以直接增加吗?
Integer temp = myMap.get(key);
temp++;
myMap.put(key, temp);
there is no way to just do this (this doesn't work) :
没有办法做到这一点(这不起作用):
myMap.get(key)++;
采纳答案by Michael Borgwardt
Do I have to return the object and then put a new one in ?
我是否必须返回对象然后放入一个新对象?
As long as you use the Integer
wrapper class yes, because it's immutable. You could use a mutable wrapper class instead, even one that has an increment()
method. However, you then lose the ability to use autoboxing and autounboxing on the values.
只要你使用Integer
包装类是的,因为它是不可变的。您可以改用可变包装类,即使是具有increment()
方法的包装类。但是,您随后将无法对值使用自动装箱和自动拆箱。
回答by Nicolas
As Integer
are immutable, yes, you have to do it that way.
If you really want to increment it directly, you'll have to write your own mutable class.
由于Integer
是不可变的,是的,你必须这样做。如果您真的想直接增加它,则必须编写自己的可变类。
回答by Bozho
You can't directly increment it, because it is immutable. You have to increment it and put the new object back.
你不能直接增加它,因为它是不可变的。您必须增加它并将新对象放回原处。
Auto boxing is also interfering here. In fact what's happening is something similar to:
自动拳击也干扰了这里。事实上,正在发生的事情类似于:
Integer i1 = getFromMap();
i1 = Integer.valueOf(++ i1.intValue());
So here your reference points to a new object. You have to put that object back in the map, under the same key.
所以在这里你的引用指向一个新对象。您必须将该对象放回地图中,使用相同的键。
回答by scheffield
First of all: be aware of unboxing: the temp is from type Integer. But the operation ++ is implemented for int. So temp is unboxed to type int. This means if temp is null you run in a NullPointerException.
首先:注意拆箱:temp 来自 Integer 类型。但是操作++是为int实现的。所以 temp 被取消装箱以输入 int。这意味着如果 temp 为 null,您将在 NullPointerException 中运行。
And you have to do it like you discripted in your first code block.
你必须像你在第一个代码块中描述的那样做。
回答by AlexR
This is the shortest code that does this job.
这是完成这项工作的最短代码。
myMap.put(key, myMap.get(key) + 1)
I think it is not too long.
我觉得不会太长。
回答by Peter Lawrey
You can use a mutable integer such as AtomicInteger.
您可以使用可变整数,例如 AtomicInteger。
Map<Key, AtomicInteger> myMap = new HashMap<Key, AtomicInteger>();
myMap.get(key).incrementAndGet();
Or you can use Trove4j which supports primitives in collections.
或者您可以使用 Trove4j,它支持集合中的原语。
TObjectIntHashMap<Key> myMap;
myMap.increment(key);
回答by leonbloy
If you have to do this more than twice you'd prefer to create a tiny class like:
如果您必须这样做两次以上,您更愿意创建一个小类,如:
public class MappedCounter {
private Map<String, Integer> map = new HashMap<String, Integer>();
public void addInt(String k, int v) {
if (!map.containsKey(k)) map.put(k, v);
else map.put(k, map.get(k) + v);
}
public int getInt(String k) {
return map.containsKey(k) ? map.get(k) : 0;
}
public Set<String> getKeys() {
return map.keySet();
}
}
回答by Jonathan Heinen
In Java 8 there are new methods on Map
which you can use with lambdas to solve this. First alternative, compute
:
在 Java 8 中有一些新方法Map
可以与 lambdas 一起使用来解决这个问题。第一个选择,compute
:
a.compute(key, (k, v) -> v+1);
Note that this only works if the hash is initialized for all possible keys.
请注意,这仅在为所有可能的键初始化散列时才有效。
If this is not guaranteed you can either change the above code to:
如果不能保证,您可以将上述代码更改为:
a.compute(key, (k, v) -> v == null ? 1 : v + 1);
Or use the merge
method (which I would prefer):
或者使用merge
方法(我更喜欢):
a.merge(key, 1, (a, b) -> a + b);
Maybe there are more lambda based methods I am not aware of.
也许还有更多我不知道的基于 lambda 的方法。
回答by MGoksu
I use the below code and it works but at the beginning you need to define a BiFunction
describing that the operation is incrementing by 1.
我使用下面的代码并且它可以工作,但是在开始时您需要定义一个BiFunction
描述该操作递增 1的描述。
public static Map<String, Integer> strInt = new HashMap<String, Integer>();
public static void main(String[] args) {
BiFunction<Integer, Integer, Integer> bi = (x,y) -> {
if(x == null)
return y;
return x+y;
};
strInt.put("abc", 0);
strInt.merge("abc", 1, bi);
strInt.merge("abc", 1, bi);
strInt.merge("abc", 1, bi);
strInt.merge("abcd", 1, bi);
System.out.println(strInt.get("abc"));
System.out.println(strInt.get("abcd"));
}
output is
输出是
3
1
回答by Tyderf
This should work
这应该工作
// If the key you want to add does not exist then add it as a new key
// And make the value 1
if (map.get(key) == null) {
map.put(key, 1);
} else {
// If the key does exist then replace the key's value with it's
// Original value plus one
map.put(key, map.get(key) + 1);
}