java 如何替换 LinkedHashMap 中特定键的值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27705908/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 12:14:56  来源:igfitidea点击:

How to Replace the value in particular key in LinkedHashMap

javaandroidcollections

提问by Abhinav singh

I want to replace the value in particular key in LinkedHashMap.

我想替换 LinkedHashMap 中特定键的值。

for example The initial Condition..

例如初始条件..

"key1" -> "value1"
"key2" -> "value2"
"key3" -> "value3"
"key4" -> "value4"
"key5" -> "value5"

I want to expected result...

我想要预期的结果...

"key1" -> "value1"
"key2" -> "value8"
"key3" -> "value3"
"key4" -> "value6"
"key5" -> "value5"

回答by Eran

You put a new value for that key :

您为该键设置了一个新值:

map.put("key2","value8");
map.put("key4","value6");

Note that for LinkedHashMap, changing the value for an existing key won't change the iteration order of the Map(which is the order in which the keys were first inserted to the Map).

请注意,对于LinkedHashMap,更改现有键的值不会更改 的迭代顺序Map(这是键首次插入到 Map 中的顺序)。

回答by Naman Gala

In Map(LinkedHashMap) key is the unique value. So whenever you try to put a value for a key, it will either add new entry in map or if key already exist then it will replace old value for that key with new value.

在 Map(LinkedHashMap) 中,键是唯一值。因此,无论何时您尝试为键输入值,它都会在映射中添加新条目,或者如果键已存在,则它将用新值替换该键的旧值。

map.put("existing key", "new value");

Above code will replace value of existing keyin map with new value.

上面的代码将existing keynew value.

回答by Rohith K

The proper way of checking if the key is present or not:

检查密钥是否存在的正确方法:

  if (map.containsKey(key)) {
      map.put("existing key", "newValue");
  }