How to get element position from Java Map

后端 未结 13 1491
执念已碎
执念已碎 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: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 linkedHashMap = new LinkedHashMap();
    
    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(linkedHashMap.values())).get(pos);
    System.out.println(value.getId());
    

提交回复
热议问题