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

时间:2021-12-22 19:15:26

How to retrieve an element from HashMap by its position, is it possible at all?

如何通过它的位置从HashMap中检索一个元素,它有可能吗?

12 个解决方案

#1


82  

HashMaps do not preserve ordering:

HashMaps不保留排序:

This class makes no guarantees as to the order of the map; in particular, it does not guarantee that the order will remain constant over time.

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

Take a look at LinkedHashMap, which guarantees a predictable iteration order.

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

#2


87  

Use a LinkedHashMap and when you need to retrieve by position, convert the values into an ArrayList.

使用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);

#3


30  

If you want to maintain the order in which you added the elements to the map, use LinkedHashMap as opposed to just HashMap.

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

Here is an approach that will allow you to get a value by its index in the map:

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

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

#4


11  

Use LinkedHashMap:

使用LinkedHashMap:

Hash table and linked list implementation of the Map interface, with predictable iteration order. This implementation differs from HashMap in that it maintains a doubly-linked list running through all of its entries.

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

#5


9  

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:

如果由于某种原因,您必须坚持使用hashMap,您可以将keySet转换为数组并索引数组中的键以获取地图中的值,如下所示:

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

You can then access the map like:

然后,您可以访问地图,如:

map.get(keys[i]);

#6


6  

Use LinkedHashMap and use this function.

使用LinkedHashMap并使用此功能。

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

Define like this and.

像这样定义和。

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;
    }

The function can return the selected entry.

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

#7


2  

HashMap - and the underlying data structure - hash tables, do not have a notion of position. Unlike a LinkedList or Vector, the input key is transformed to a 'bucket' where the value is stored. These buckets are not ordered in a way that makes sense outside the HashMap interface and as such, the items you put into the HashMap are not in order in the sense that you would expect with the other data structures

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

#8


2  

HashMap has no concept of position so there is no way to get an object by position. Objects in Maps are set and get by keys.

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

#9


2  

I'm assuming by 'position' you're referring to the order in which you've inserted the elements into the HashMap. In that case you want to be using a LinkedHashMap. The LinkedHashMap doesn't offer an accessor method however; you will need to write one like

我假设“位置”你指的是你将元素插入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 don't allow access by position, it only knows about the hash code and and it can retrieve the value if it can calculate the hash code of the key. TreeMaps have a notion of ordering. Linkedhas maps preserve the order in which they entered the map.

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

#11


1  

Another working approach is transforming map values into an array and then retrieve element at index. Test run of 100 000 element by index searches in LinkedHashMap of 100 000 objects using following approaches led to following results:

另一种工作方法是将映射值转换为数组,然后在索引处检索元素。通过使用以下方法在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

All in all retrieving element by index from LinkedHashMap seems to be pretty heavy operation.

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

#12


0  

You can try to implement something like that, look at:

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

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

I hope this works for you.

我希望这适合你。

#1


82  

HashMaps do not preserve ordering:

HashMaps不保留排序:

This class makes no guarantees as to the order of the map; in particular, it does not guarantee that the order will remain constant over time.

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

Take a look at LinkedHashMap, which guarantees a predictable iteration order.

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

#2


87  

Use a LinkedHashMap and when you need to retrieve by position, convert the values into an ArrayList.

使用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);

#3


30  

If you want to maintain the order in which you added the elements to the map, use LinkedHashMap as opposed to just HashMap.

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

Here is an approach that will allow you to get a value by its index in the map:

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

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

#4


11  

Use LinkedHashMap:

使用LinkedHashMap:

Hash table and linked list implementation of the Map interface, with predictable iteration order. This implementation differs from HashMap in that it maintains a doubly-linked list running through all of its entries.

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

#5


9  

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:

如果由于某种原因,您必须坚持使用hashMap,您可以将keySet转换为数组并索引数组中的键以获取地图中的值,如下所示:

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

You can then access the map like:

然后,您可以访问地图,如:

map.get(keys[i]);

#6


6  

Use LinkedHashMap and use this function.

使用LinkedHashMap并使用此功能。

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

Define like this and.

像这样定义和。

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;
    }

The function can return the selected entry.

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

#7


2  

HashMap - and the underlying data structure - hash tables, do not have a notion of position. Unlike a LinkedList or Vector, the input key is transformed to a 'bucket' where the value is stored. These buckets are not ordered in a way that makes sense outside the HashMap interface and as such, the items you put into the HashMap are not in order in the sense that you would expect with the other data structures

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

#8


2  

HashMap has no concept of position so there is no way to get an object by position. Objects in Maps are set and get by keys.

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

#9


2  

I'm assuming by 'position' you're referring to the order in which you've inserted the elements into the HashMap. In that case you want to be using a LinkedHashMap. The LinkedHashMap doesn't offer an accessor method however; you will need to write one like

我假设“位置”你指的是你将元素插入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 don't allow access by position, it only knows about the hash code and and it can retrieve the value if it can calculate the hash code of the key. TreeMaps have a notion of ordering. Linkedhas maps preserve the order in which they entered the map.

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

#11


1  

Another working approach is transforming map values into an array and then retrieve element at index. Test run of 100 000 element by index searches in LinkedHashMap of 100 000 objects using following approaches led to following results:

另一种工作方法是将映射值转换为数组,然后在索引处检索元素。通过使用以下方法在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

All in all retrieving element by index from LinkedHashMap seems to be pretty heavy operation.

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

#12


0  

You can try to implement something like that, look at:

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

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

I hope this works for you.

我希望这适合你。