How to get element position from Java Map
java
Solution
Though a bit late to answer. But the option is to use `LinkedHashMap`: this map preserves the order according to insertion of elements, as everyone has suggested. However, As a warning, it has a constructor `LinkedHashMap(int initialCapacity, float loadFactor, boolean accessOrder)` which will create a linked hash map whose order of iteration is the order in which its entries were last `accessed`. Don't use this constructor for this case.
However, if I needed such functionality, i would extend it and implement my necessary function to re-use them in OOP way.
class MyLinkedMap<K, V> extends LinkedHashMap<K, V>
{
public V getValue(int i)
{
Map.Entry<K, V>entry = this.getEntry(i);
if(entry == null) return null;
return entry.getValue();
}
public Map.Entry<K, V> getEntry(int i)
{
// check if negetive index provided
Set<Map.Entry<K,V>>entries = entrySet();
int j = 0;
for(Map.Entry<K, V>entry : entries)
if(j++ == i)return entry;
return null;
}
}
Now i can instantiate it and can get a entry and value either way i want:
MyLinkedMap<String, Integer>map = new MyLinkedMap<>();
map.put("a first", 1);
map.put("a second", 2);
map.put("a third", 3);
System.out.println(map.getValue(2));
System.out.println(map.getEntry(1));
Output:
3
a second=2
Problem
I have this Java Map: Can you tell me how I can get the 6-th element of the Map? ``` private static final Map<String, Users> cache = new HashMap<>(); ``` is this possible? Or I have to use another Java collection?