How to replace value in a specific key in LinkedHashMap

I want to replace the value in a specific key in LinkedHashMap.

e.g. Initial condition.

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

I want to expect a result ...

 "key1" -> "value1" "key2" -> "value8" "key3" -> "value3" "key4" -> "value6" "key5" -> "value5" 
+6
source share
3 answers

You have added a new value for this key:

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

Note that for LinkedHashMap changing the value for an existing key will not change the Map iteration order (which is the order in which the keys were first inserted into the map).

+14
source

In Map (LinkedHashMap), a key is a unique value. Therefore, whenever you try to put a value for a key, it will either add a new record to the card, or the key already exists, and then replace the old value for this key with a new value.

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

Above, the code will replace the existing key value on the map with the new value .

+2
source

The correct way to check for a key or not:

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

Source: https://habr.com/ru/post/980306/


All Articles