How to get element position from Java Map

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

    HashMap doesn't grantee the order. If you concern about order you should use LinkedHashMap

    Map orderedMap=new LinkedHashMap<>();
    

    Now when you put an element it will keep the order what you put.

    If you want to get 6th element, now you can do it since you have your elements in order.

     orderedMap.values().toArray()[5]// will give you 6th value in the map. 
    

    Example

     Map orderedMap=new LinkedHashMap<>();
     orderedMap.put("a","a");
     orderedMap.put("b","b");
     System.out.println(orderedMap.values().toArray()[1]);  // you will get b(value)
     System.out.println(orderedMap.keySet().toArray()[1]);  // you will get b(key)
        }
    

提交回复
热议问题