Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combining remove and put method in LinkedHashMap

With a LinkedHashMap, when I try to reinsert same key with different value, it replaces the value and maintains the order of key i.e if I do this

Map<String,String> map = new LinkedHashMap<>();
map.put("a", "a");
map.put("b", "b");
map.put("c", "c");
map.put("d", "d");
map.values().stream().forEach(System.out::print);    

Output: abcd

Now if I add in the map a different value with same key,the order remains the same i.e

map.put("b", "j");
map.values().stream().forEach(System.out::print); 

Output: ajcd

Is there any other way? One is to remove and reinsert key with new value, which prints acdj as output. In my case I want to do it for multiple keys based on some property of object used as value?

Solution using streams would be preferable.

like image 994
Jaspreet Jolly Avatar asked Mar 13 '26 03:03

Jaspreet Jolly


1 Answers

This linked list defines the iteration ordering, which is normally the order in which keys were inserted into the map (insertion-order). Note that insertion order is not affected if a key is re-inserted into the map

LinkedHashMap javadoc.

it keep track of the keys insertion, and if we add the Map.put javadoc :

If the map previously contained a mapping for the key, the old value is replaced by the specified value.

Map javadoc

The Entry is not replace, only the value is modified so the key remains the same.

You need to remove and then insert the value to update the ordering of the keys.

like image 134
AxelH Avatar answered Mar 14 '26 17:03

AxelH