Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get key position from a HashMap in Java

Tags:

java

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);
like image 246
aNNgeL0 Avatar asked Feb 18 '15 20:02

aNNgeL0


1 Answers

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
like image 73
Adam Avatar answered Sep 27 '22 16:09

Adam