16

I want to replace the value in particular key in 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"
Abhinav singh
  • 1,448
  • 1
  • 14
  • 31

3 Answers3

34

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).

Eran
  • 387,369
  • 54
  • 702
  • 768
  • 4
    Actually you can choose whether you want the LinkedHashMap iteration in insertion-order or access-order – lbalazscs Dec 30 '14 at 13:16
  • 1
    @lbalazscs Oh, you're right. Insertion order is the default, but there's a constructor that allows you to override this default. – Eran Dec 30 '14 at 13:21
3

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.put("existing key", "new value");

Above code will replace value of existing key in map with new value.

Naman Gala
  • 4,670
  • 1
  • 21
  • 55
1

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

  if (map.containsKey(key)) {
      map.put("existing key", "newValue");
  }
Appulus
  • 18,630
  • 11
  • 38
  • 46
Rohith K
  • 1,433
  • 10
  • 15
  • The OP wasn't asking to check if a key is present. Using a put will either add if it's not there, or replace if a key is there. There's no need to check if a key exists beforehand for this. – Raid Feb 15 '22 at 15:51