Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Replace the value in particular key in LinkedHashMap

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"
like image 609
Abhinav singh Avatar asked Dec 30 '14 12:12

Abhinav singh


People also ask

How do you change a value in a Hashtable in Java?

You can use computeIfPresent method and supply it a mapping function, which will be called to compute a new value based on existing one. For example, Map<String, Integer> words = new HashMap<>(); words. put("hello", 3); words.

Does LinkedHashMap allow duplicate values?

A LinkedHashMap cannot contain duplicate keys. LinkedHashMap can have null values and the null key. Unlike HashMap, the iteration order of the elements in a LinkedHashMap is predictable. Just like HashMap, LinkedHashMap is not thread-safe.


2 Answers

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

like image 111
Eran Avatar answered Oct 11 '22 09:10

Eran


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.

like image 40
Naman Gala Avatar answered Oct 11 '22 08:10

Naman Gala