如何从Java Map获取元素位置 [英] How to get element position from Java Map
问题描述
我有这张Java地图:
I have this Java Map:
你能告诉我如何获得地图的第6个元素吗?
Can you tell me how I can get the 6-th element of the Map?
private static final Map<String, Users> cache = new HashMap<>();
这可能吗?或者我必须使用另一个Java集合?
is this possible? Or I have to use another Java collection?
推荐答案
虽然回答有点迟。但是可以选择使用 LinkedHashMap
:这个地图根据元素的插入保留了顺序,正如大家所建议的那样。但是,作为警告,它有一个构造函数 LinkedHashMap(int initialCapacity,float loadFactor,boolean accessOrder)
,它将创建一个链接的哈希映射,其迭代顺序是其中的顺序它的条目是最后访问
。在这种情况下不要使用这个构造函数。
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.
但是,如果我需要这样的功能,我会扩展它并实现我的必要功能,以OOP方式重用它们。
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));
输出:
3
a second=2
这篇关于如何从Java Map获取元素位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!