在java hashmap中给定一个键,如何增加值?

在java hashmap中给定一个键,如何增加值?,java,hashmap,Java,Hashmap,如果我有以下资料: public enum Attribute { ONE, TWO, THREE } private Map<String, Integer> mAttributesMap = new HashMap<>(); mAttributesMap.put(Attribute.ONE.name(), 5); mAttributesMap.put(Attribute.TWO.name(), 5); int currentValue = mAttri

如果我有以下资料:

public enum Attribute {
     ONE, TWO, THREE
}

private Map<String, Integer> mAttributesMap = new HashMap<>();

mAttributesMap.put(Attribute.ONE.name(), 5);
mAttributesMap.put(Attribute.TWO.name(), 5);
int currentValue = mAttributesMap.get(Attribute.ONE.name());
mAttributesMap.put(Attribute.ONE.name(), currentValue+1);
int currentValue = 0;
if (mAttributesMap.containsKey(Attribute.ONE.name())) {
  currentValue = mAttributesMap.get(Attribute.ONE.name());
}
mAttributesMap.put(Attribute.ONE.name(), currentValue+1);
公共枚举属性{
一,二,三
}
私有映射mAttributesMap=newhashmap();
mAttributesMap.put(Attribute.ONE.name(),5);
mAttributesMap.put(Attribute.TWO.name(),5);

那么如何获取
mAttibutesMap
的密钥呢?以及如何增加它?

您不能直接编辑地图,但可以使用以下方法替换值:

mAttributesMap.put(Attribute.ONE.name(), 10);

1。首先,您可以直接使用
Map
put
如下:

mAttributesMap.put(Attribute.ONE, 5);
mAttributesMap.put(Attribute.TWO, 5);

2.要增加键的值,您可以执行以下操作,获取值,然后
使用
+1
再次放置
,因为
键已经存在,它只会替换现有的键(地图中的键是唯一的):


3.要获得更通用的解决方案,您可以执行以下操作:

public void incrementValueFromKey(Attribute key, int increment){
    mAttributesMap.computeIfPresent(key, (k, v) -> v + increment);
}

如果知道HashMap中存在密钥,则可以执行以下操作:

public enum Attribute {
     ONE, TWO, THREE
}

private Map<String, Integer> mAttributesMap = new HashMap<>();

mAttributesMap.put(Attribute.ONE.name(), 5);
mAttributesMap.put(Attribute.TWO.name(), 5);
int currentValue = mAttributesMap.get(Attribute.ONE.name());
mAttributesMap.put(Attribute.ONE.name(), currentValue+1);
int currentValue = 0;
if (mAttributesMap.containsKey(Attribute.ONE.name())) {
  currentValue = mAttributesMap.get(Attribute.ONE.name());
}
mAttributesMap.put(Attribute.ONE.name(), currentValue+1);
如果HashMap中可能存在或不存在密钥,则可以执行以下操作:

public enum Attribute {
     ONE, TWO, THREE
}

private Map<String, Integer> mAttributesMap = new HashMap<>();

mAttributesMap.put(Attribute.ONE.name(), 5);
mAttributesMap.put(Attribute.TWO.name(), 5);
int currentValue = mAttributesMap.get(Attribute.ONE.name());
mAttributesMap.put(Attribute.ONE.name(), currentValue+1);
int currentValue = 0;
if (mAttributesMap.containsKey(Attribute.ONE.name())) {
  currentValue = mAttributesMap.get(Attribute.ONE.name());
}
mAttributesMap.put(Attribute.ONE.name(), currentValue+1);
我希望这对你有帮助!非常感谢。和平


p、 这是我于2018年3月22日8:22更新的David Geirola答案。

地图有
get
put
方法,您是否尝试使用它们检索值、增加值并重新设置?请发布您的尝试为什么它是
地图
而不是
地图
?请考虑接受答案,这就是论坛的工作方式,新用户会更喜欢接受的帖子而不是不接受的帖子