How to get element position from Java Map

后端 未结 13 1532
执念已碎
执念已碎 2021-01-07 20:11

I have this Java Map:

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

private static final Map cache = new HashMap<         


        
13条回答
  •  梦谈多话
    2021-01-07 20:42

    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.

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

    UPDATE:

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

    LinkedHashMap linkedHashMap = new LinkedHashMap();
    // or LinkedHashMap 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(linkedHashMap.values())).get(pos);
    System.out.println(tmp.getName());
    

提交回复
热议问题