Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java LinkedHashMap replace key

Tags:

java

map

Is there any way to replace a key using put() in a LinkedHashMap without losing the order that the key was originally inserted in?

like image 841
wgoodall01 Avatar asked Aug 26 '14 13:08

wgoodall01


People also ask

How do I change a key in LinkedHashMap?

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.

How do I change the value of a LinkedHashMap in Java?

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");

Can we store null key in LinkedHashMap?

LinkedHashMap allows one null key and multiple null values. LinkedHashMap maintains order in which key-value pairs are inserted.


1 Answers

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.

like image 54
Mena Avatar answered Sep 21 '22 23:09

Mena