Is there any way to replace a key using put()
in a LinkedHashMap without losing the order that the key was originally inserted in?
If you have to do it on a linkedhashmap, you can create a new LinkedHashMap, iterate the old one and put into the new one, when your target entry comes, create a new entry with different key, put the new entry into the map.
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");
LinkedHashMap allows one null key and multiple null values. LinkedHashMap maintains order in which key-value pairs are inserted.
You do not lose the order when putting a different value for the same key.
Example
Map<String, String> map = new LinkedHashMap<String, String>();
map.put("foo", "bar");
map.put("blah", "baz");
System.out.println(map);
map.put("foo", "foo");
System.out.println(map);
Output
{foo=bar, blah=baz}
{foo=foo, blah=baz}
Edit
"Replacing" a key for a given value would imply removing the key value pair, then putting the new key with the stored value.
As such, there is no direct way to do this with a LinkedHashMap
, probably not even by inheriting and changing the behavior of remove
and put
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With