How to add element at specific index/position in LinkedHashMap?

You could do this element adding to 1. or last place:

Adding to last place ► You just need to remove the previous entry from the map like this:

map.remove(key);
map.put(key,value);

Adding to first place ► It’s a bit more complicated, you need to clone the map, clear it, put the 1. value to it, and put the new map to it, like this:

I’m using maps with String keys and Group (my custom class) values:

LinkedHashMap<String, Group> newMap=(LinkedHashMap<String, Group>) map.clone();
map.clear();
map.put(key, value);
map.putAll(newMap);

As you see, with these methods you can add unlimited amount of things to the begin and to the end of the map.

Leave a Comment