Is it possible to get element from HashMap by its position?

后端 未结 14 1326
时光说笑
时光说笑 2020-12-12 18:31

How to retrieve an element from HashMap by its position, is it possible at all?

相关标签:
14条回答
  • 2020-12-12 19:26

    If you, for some reason, have to stick with the hashMap, you can convert the keySet to an array and index the keys in the array to get the values in the map like so:

    Object[] keys = map.keySet().toArray();
    

    You can then access the map like:

    map.get(keys[i]);
    
    0 讨论(0)
  • 2020-12-12 19:30

    You can try to implement something like that, look at:

    Map<String, Integer> map = new LinkedHashMap<String, Integer>();
    map.put("juan", 2);
    map.put("pedro", 3);
    map.put("pablo", 5);
    map.put("iphoncio",9)
    
    List<String> indexes = new ArrayList<String>(map.keySet()); // <== Parse
    
    System.out.println(indexes.indexOf("juan"));     // ==> 0
    System.out.println(indexes.indexOf("iphoncio"));      // ==> 3
    

    I hope this works for you.

    0 讨论(0)
提交回复
热议问题