I read lines from a file and load them into a LinkedHashMap to preserve the insertion order. At a certain point of my algorithm I have to modify both a key and it’s corresponding value without affecting the insertion order. Here is an example :
This is the initial content of my LinkedHashMap
"k1" -> "v1"
"k2" -> "v2"
"k3" -> "v3"
"k4" -> "v4"
"k5" -> "v5"
I want to modify k3 and v3 so that I get :
"k1" -> "v1"
"k2" -> "v2"
"k33" -> "v33"
"k4" -> "v4"
"k5" -> "v5"
But if I use
map.remove("k3");
map.put("k33", "v33");
Then what I get instead is :
"k1" -> "v1"
"k2" -> "v2"
"k4" -> "v4"
"k5" -> "v5"
"k33" -> "v33"
Which is a perfectly normal behavior, but not what I wanted to do.
If the order of the enteries is important, I’d keep a separate list that maintains that order – this will make it obvious to anyone subsequently looking at your code what’s going on.