How to get key position from a HashMap in Java

java

Solution

As other answers state you need to use a structure like `java.util.LinkedHashMap`. LinkedHashMap maintains its keys internally using a `LinkedEntrySet`, this does not formally provide order, but iterates in the insertion order used.

If you pass the `Map.keySet()` into a List implementation you can make use of the `List.indexOf(Object)` method without having to write any of the extra code in the other answer.

Map<String, Integer> map = new LinkedHashMap<String, Integer>();
map.put("Audi", 3);
map.put("BMW", 5);
map.put("Vauxhall", 7);

List<String> indexes = new ArrayList<String>(map.keySet()); // <== Set to List

// BOOM !

System.out.println(indexes.indexOf("Audi"));     // ==> 0
System.out.println(indexes.indexOf("BMW"));      // ==> 1
System.out.println(indexes.indexOf("Vauxhall")); // ==> 2

Problem

How can I get the key position in the map? How can I see on which position is "Audi" and "BMW"? ``` Map<String, Integer> map = new HashMap<String, Integer>(); map.put("Audi", 3); map.put("BMW", 5); ```

Original source