Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have an ordered LinkedHashMap and i want to add element at specific index , say at first place or last place in the map. How can i add element in LinkedHashMap at an specific position?

Even if I could add an element to FIRST or LAST position in LinkedHashMap would help!

like image 793
supernova Avatar asked Oct 06 '11 20:10

supernova


People also ask

How do I add elements to LinkedHashMap?

Use the put() method to add elements to LinkedHashMap collection.

How do I find index in LinkedHashMap?

Method 1(Using keys array): You can convert all the keys of LinkedHashMap to a set using Keyset method and then convert the set to an array by using toArray method now using array index access the key and get the value from LinkedHashMap. Parameters: The method does not take any parameters.

How insertion order is maintained in LinkedHashMap?

It maintains a linkedlist of the entries in the map in the order in which they were inserted. This helps to maintain iteration order and elements will be returned in the order they were first added in.


2 Answers

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.

like image 142
gyurix Avatar answered Oct 13 '22 02:10

gyurix


You can not change the order. It is insert-order (by default) or access-order with this constructor:

public LinkedHashMap(int initialCapacity, float loadFactor, boolean accessOrder)

  • Constructs an empty LinkedHashMap instance with the specified initial capacity, load factor and ordering mode.

  • Parameters: initialCapacity - the initial capacity loadFactor - the load factor accessOrder - the ordering mode - true for access-order, false for insertion-order

  • Throws: IllegalArgumentException - if the initial capacity is negative or the load factor is nonpositive

See: LinkedHashMap

like image 44
MasterCassim Avatar answered Oct 13 '22 00:10

MasterCassim