如何从 Java Map 获取元素位置

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20240408/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 00:30:44  来源:igfitidea点击:

How to get element position from Java Map

java

提问by Peter Penzov

I have this Java Map:

我有这个 Java 地图:

Can you tell me how I can get the 6-th element of the Map?

你能告诉我如何获得地图的第 6 个元素吗?

private static final Map<String, Users> cache = new HashMap<>();

is this possible? Or I have to use another Java collection?

这可能吗?或者我必须使用另一个 Java 集合?

采纳答案by Sage

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.

虽然回答有点晚。但是可以选择使用LinkedHashMap:正如每个人所建议的那样,此映射根据元素的插入保留顺序。但是,作为警告,它有一个构造函数LinkedHashMap(int initialCapacity, float loadFactor, boolean accessOrder),它将创建一个链接的哈希映射,其迭代顺序是其条目最后的顺序accessed。在这种情况下不要使用此构造函数。

However, if I needed such functionality, i would extend it and implement my necessary function to re-use them in OOP way.

但是,如果我需要这样的功能,我会扩展它并实现我的必要功能,以便以 OOP 方式重用它们。

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

回答by kutschkem

With guava's Iterables

使用番石榴的可迭代对象

Iterables.get(map.entrySet(),6);

回答by Foolish

Correct!! you will have to use other collection for getting values on index(position). You can use ArrayList

正确的!!您将不得不使用其他集合来获取索引(位置)的值。您可以使用ArrayList

回答by Vignesh Vino

The HashMaphas no defined ordering of keys.It's Unordered.

HashMap没有定义的keys.It的无序的顺序。

You can use LinkedHashMapwhich will store your keys in order of insertion.You can retrieve them by calling keySet().

您可以使用LinkedHashMapwhich 将按插入顺序存储您的密钥。您可以通过调用keySet()来检索它们。

回答by SudoRahul

A HashMapdoes not maintain the order of the elements inserted in it. You can used a LinkedHashMapinstead which maintains the order of the elements inserted in it.

AHashMap不保持插入其中的元素的顺序。您可以使用 aLinkedHashMap来维护插入其中的元素的顺序。

Though you need to note that even a LinkedHashMaphas no such method which would give the element at a particular index. You will have to manually iterate through the entries and extract the element at the 6th iteration.

尽管您需要注意,即使 aLinkedHashMap也没有这样的方法可以在特定索引处提供元素。您必须手动遍历条目并在第 6 次迭代时提取元素。

回答by Abimaran Kugathasan

There is no Order in HashMap. You can obtain the list of may keys using map.keySet()but there's no guarantee the key set will be in the order which you add it in. Use LinkedHashMapinstead of HashMapIt will always return keys in same order (as insertion)

中没有订单HashMap。您可以使用获取可能键的列表,map.keySet()但不能保证键集将按照您添加它的顺序。使用LinkedHashMap代替HashMap它将始终以相同的顺序返回键(作为插入)

回答by Kayaman

A HashMapdoesn't have a position. You can iterate through its KeySetor EntrySet, and pick the nth element, but it's not really the same as a position. A LinkedHashMapdoes have a position, since it has a predictable iteration order.

AHashMap没有位置。您可以遍历它的KeySetor EntrySet,然后选择第 n 个元素,但这与位置实际上并不相同。一个LinkedHashMap中确实有一个位置,因为它有一个可预知的迭代顺序。

回答by vikingsteve

If the ordering is to mean anything significant, you could consider using a SortedMap.

如果排序意味着任何重要的事情,您可以考虑使用SortedMap

Concrete implementation: TreeMap

具体实现: TreeMap

回答by Adam Arold

You need to use a LinkedHashMapin order to be able to tell the order of the inserted elements. HashMapis not capable of doing so.

您需要使用 aLinkedHashMap才能知道插入元素的顺序。HashMap没有能力这样做。

回答by MaVRoSCy

According to documentation, HashMap is a Hash table based implementation of the Map interface. This implementation provides all of the optional map operations, and permits null values and the null key. (The HashMap class is roughly equivalent to Hashtable, except that it is unsynchronized and permits nulls.) 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.

根据文档,HashMap 是 Map 接口的基于哈希表的实现。此实现提供所有可选的映射操作,并允许空值和空键。(HashMap 类大致等同于 Hashtable,只是它是非同步的并且允许空值。)该类不保证映射的顺序;特别是,它不保证订单会随着时间的推移保持不变。

That's why it is not wise to use this kind of Collection.

这就是为什么使用这种 Collection 是不明智的。

UPDATE:

更新:

Based on @Prateek implementation of LinkedHashMap I would suggest something like:

基于 LinkedHashMap 的 @Prateek 实现,我建议如下:

LinkedHashMap<String,User> linkedHashMap = new LinkedHashMap<String,User>();
// or LinkedHashMap<String,User> linkedHashMap = new LinkedHashMap<>(); //for java 7+

linkedHashMap.put("1",userObj1);
linkedHashMap.put("2",userObj2);
linkedHashMap.put("3",userObj3);

/* Get by position */
int pos = 1; // Your position
User tmp= (new ArrayList<User>(linkedHashMap.values())).get(pos);
System.out.println(tmp.getName());

回答by Prateek

HashMapsdo not preserve ordering:

HashMap不保留顺序:

LinkedHashMapwhich guarantees a predictable iteration order.

LinkedHashMap保证可预测的迭代顺序。

Example

例子

public class Users 
{
 private String Id;

 public String getId()
 {
    return Id;
 }

 public void setId(String id) 
 {
    Id = id;
 }
}


Users user;
LinkedHashMap<String,Users> linkedHashMap = new LinkedHashMap<String,Users>();

for (int i = 0; i < 3; i++)
{
  user = new Users();
  user.setId("value"+i);
  linkedHashMap.put("key"+i,user);
}

/* Get by position */
int pos = 1;
Users value = (new ArrayList<Users>(linkedHashMap.values())).get(pos);
System.out.println(value.getId());