是否可以通过其位置从HashMap获取元素?

时间:2011-03-08 19:10:44

标签: java hashmap

如何从HashMap的位置检索元素,是否可以呢?

14 个答案:

答案 0 :(得分:98)

使用LinkedHashMap,当您需要按位置检索时,将值转换为ArrayList。

LinkedHashMap<String,String> linkedHashMap = new LinkedHashMap<String,String>();
/* Populate */
linkedHashMap.put("key0","value0");
linkedHashMap.put("key1","value1");
linkedHashMap.put("key2","value2");
/* Get by position */
int pos = 1;
String value = (new ArrayList<String>(linkedHashMap.values())).get(pos);

答案 1 :(得分:88)

HashMaps不保留排序:

  

本课程不保证   地图的顺序;特别是,   它不保证订单   随着时间的推移会保持不变。

查看LinkedHashMap,它保证了可预测的迭代顺序。

答案 2 :(得分:42)

如果您想维护将元素添加到地图的顺序,请使用LinkedHashMap而不是HashMap

这是一种允许您通过地图中的索引获取值的方法:

public Object getElementByIndex(LinkedHashMap map,int index){
    return map.get( (map.keySet().toArray())[ index ] );
}

答案 3 :(得分:15)

If you, for some reason, have to stick with the hashMap, you can convert the keySet to an array and index the keys in the array to get the values in the map like so:

Object[] keys = map.keySet().toArray();

You can then access the map like:

map.get(keys[i]);

答案 4 :(得分:12)

使用LinkedHashMap

  

Map接口的哈希表和链表实现,具有可预测的迭代顺序。此实现与HashMap的不同之处在于它维护了一个贯穿其所有条目的双向链表。

答案 5 :(得分:6)

使用LinkedHashMap并使用此功能。

private LinkedHashMap<Integer, String> map = new LinkedHashMap<Integer, String>();

像这样定义和。

private Entry getEntry(int id){
        Iterator iterator = map.entrySet().iterator();
        int n = 0;
        while(iterator.hasNext()){
            Entry entry = (Entry) iterator.next();
            if(n == id){
                return entry;
            }
            n ++;
        }
        return null;
    }

该函数可以返回所选条目。

答案 6 :(得分:3)

另一种工作方法是将地图值转换为数组,然后在索引处检索元素。通过使用以下方法在LinkedHashMap中对10万个对象进行索引搜索来测试运行100 000个元素,得到以下结果:

//My answer:
public Particle getElementByIndex(LinkedHashMap<Point, Particle> map,int index){
    return map.values().toArray(new Particle[map.values().size()])[index];
} //68 965 ms

//Syd Lambert's answer:
public Particle getElementByIndex(LinkedHashMap<Point, Particle> map,int index){
    return map.get( (map.keySet().toArray())[ index ] );
} //80 700 ms

总而言之,从LinkedHashMap按索引检索元素似乎是非常繁重的操作。

答案 7 :(得分:2)

HashMap - 以及底层数据结构 - 哈希表,没有位置概念。与LinkedList或Vector不同,输入键被转换为存储值的“桶”。这些存储桶不是以在HashMap接口之外有意义的方式排序的,因此,您放入HashMap的项目在某种意义上并不符合您对其他数据结构的预期

答案 8 :(得分:2)

HashMap没有位置概念,因此无法按位置获取对象。地图中的对象是按键设置和获取的。

答案 9 :(得分:2)

我假设“位置”你指的是你将元素插入HashMap的顺序。在这种情况下,您希望使用LinkedHashMap。但是LinkedHashMap不提供访问器方法;你需要写一个像

public Object getElementAt(LinkedHashMap map, int index) {
    for (Map.Entry entry : map.entrySet()) {
        if (index-- == 0) {
            return entry.value();
        }
    }
    return null;
}

答案 10 :(得分:1)

HashMaps不允许按位置访问,它只知道哈希码,并且如果它可以计算密钥的哈希码,它可以检索该值。 TreeMaps有一个排序的概念。 Linkedhas地图保留了他们进入地图的顺序。

答案 11 :(得分:1)

您可以使用以下代码获取密钥: String [] keys = (String[]) item.keySet().toArray(new String[0]);

并使用以下项的键获取插入到HashMap中的对象或列表,如下所示: item.get(keys[position]);

答案 12 :(得分:1)

默认情况下,java LinkedHasMap不支持按位置获取值。因此,我建议您使用自定义的IndexedLinkedHashMap

public class IndexedLinkedHashMap<K, V> extends LinkedHashMap<K, V> {

    private ArrayList<K> keysList = new ArrayList<>();

    public void add(K key, V val) {
        super.put(key, val);
        keysList.add(key);
    }

    public void update(K key, V val) {
        super.put(key, val);
    }

    public void removeItemByKey(K key) {
        super.remove(key);
        keysList.remove(key);
    }

    public void removeItemByIndex(int index) {
        super.remove(keysList.get(index));
        keysList.remove(index);
    }

    public V getItemByIndex(int i) {
        return (V) super.get(keysList.get(i));
    }

    public int getIndexByKey(K key) {
        return keysList.indexOf(key);
    }
}

然后,您可以将此自定义的LinkedHasMap用作

IndexedLinkedHashMap<String,UserModel> indexedLinkedHashMap=new IndexedLinkedHashMap<>();

要添加值

indexedLinkedHashMap.add("key1",UserModel);

通过索引获取价值

indexedLinkedHashMap.getItemByIndex(position);

答案 13 :(得分:0)

你可以尝试实现类似的东西,看看:

Map<String, Integer> map = new LinkedHashMap<String, Integer>();
map.put("juan", 2);
map.put("pedro", 3);
map.put("pablo", 5);
map.put("iphoncio",9)

List<String> indexes = new ArrayList<String>(map.keySet()); // <== Parse

System.out.println(indexes.indexOf("juan"));     // ==> 0
System.out.println(indexes.indexOf("iphoncio"));      // ==> 3

我希望这适合你。