How to get element position from Java Map

后端 未结 13 1367
执念已碎
执念已碎 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:46

    A HashMap does not maintain the order of the elements inserted in it. You can used a LinkedHashMap instead which maintains the order of the elements inserted in it.

    Though you need to note that even a LinkedHashMap has 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.

    0 讨论(0)
  • 2021-01-07 20:47

    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 LinkedHashMap instead of HashMap It will always return keys in same order (as insertion)

    0 讨论(0)
  • 2021-01-07 20:53

    HashMaps do not preserve ordering:

    LinkedHashMap which guarantees a predictable iteration order.

    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());
    
    0 讨论(0)
  • 2021-01-07 20:56

    You need to use a LinkedHashMap in order to be able to tell the order of the inserted elements. HashMap is not capable of doing so.

    0 讨论(0)
  • 2021-01-07 20:57

    A HashMap doesn't have a position. You can iterate through its KeySet or EntrySet, and pick the nth element, but it's not really the same as a position. A LinkedHashMap does have a position, since it has a predictable iteration order.

    0 讨论(0)
  • 2021-01-07 20:58

    Use LinkedHashMap instead of HashMap It will return keys in same order (as insertion) when calling keySet().

    For mare detail about LinkedHashMap see this

    For example to get the element from specific index

    Create a new list from your values and get the value based on index.

     LinkedHashMap<String, List<String>> hMap;
     List<List<String>> l = new ArrayList<List<String>>(hMap.values());
     l.get(6); 
    
    0 讨论(0)
提交回复
热议问题