[java] Java - get index of key in HashMap?

In java if I am looping over the keySet() of a HashMap, how do I (inside the loop), get the numerical index of that key?

Basically, as I loop through the map, I want to be able to get 0,1,2...I figure this would be cleaner than declaring an int and incrementing with each iteration.

Thanks.

This question is related to java iteration hashmap

The answer is


Simply put, hash-based collections aren't indexed so you have to do it manually.


I was recently learning the concepts behind Hashmap and it was clear that there was no definite ordering of the keys. To iterate you can use:

Hashmap<String,Integer> hs=new Hashmap();
for(Map.Entry<String, Integer> entry : hs.entrySet()){
      String key=entry.getKey();
      int val=entry.getValue();
      //your code block  
  }

I don't know is this what you're looking for

List keys = new ArrayList(map.keySet());
int index = keys.indexOf(element);

Use LinkedHashMap instead of HashMap It will always return keys in same order (as insertion) when calling keySet()

For more detail, see Class LinkedHashMap


The HashMap has no defined ordering of keys.


You can't - a set is unordered, so there's no index provided. You'll have to declare an int, as you say. Just remember that the next time you call keySet() you won't necessarily get the results in the same order.


Not sure if this is any "cleaner", but:

List keys = new ArrayList(map.keySet());
for (int i = 0; i < keys.size(); i++) {
    Object obj = keys.get(i);
    // do stuff here
}

If all you are trying to do is get the value out of the hashmap itself, you can do something like the following:

for (Object key : map.keySet()) {
    Object value = map.get(key);
    //TODO: this
}

Or, you can iterate over the entries of a map, if that is what you are interested in:

for (Map.Entry<Object, Object> entry : map.entrySet()) {
    Object key = entry.getKey();
    Object value = entry.getValue();
    //TODO: other cool stuff
}

As a community, we might be able to give you better/more appropriate answers if we had some idea why you needed the indexes or what you thought the indexes could do for you.


Posting this as an equally viable alternative to @Binil Thomas's answer - tried to add it as a comment, but was not convinced of the readability of it all.

int index = 0;

for (Object key : map.keySet()) {
   Object value = map.get(key);
   ++index;
}

Probably doesn't help the original question poster since this is the literal situation they were trying to avoid, but may aid others searching for an easy answer.


Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to iteration

Is there a way in Pandas to use previous row value in dataframe.apply when previous value is also calculated in the apply? How to loop over grouped Pandas dataframe? How to iterate through a list of dictionaries in Jinja template? How to iterate through an ArrayList of Objects of ArrayList of Objects? Ways to iterate over a list in Java Python list iterator behavior and next(iterator) How to loop through an array containing objects and access their properties recursion versus iteration What is the perfect counterpart in Python for "while not EOF" How to iterate over a JavaScript object?

Examples related to hashmap

How to split a string in two and store it in a field Printing a java map Map<String, Object> - How? Hashmap with Streams in Java 8 Streams to collect value of Map How to convert String into Hashmap in java Convert object array to hash map, indexed by an attribute value of the Object HashMap - getting First Key value The type java.util.Map$Entry cannot be resolved. It is indirectly referenced from required .class files Sort Go map values by keys Print all key/value pairs in a Java ConcurrentHashMap creating Hashmap from a JSON String