views:

751

answers:

5

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.

+2  A: 

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

Esko
+9  A: 

The HashMap has no defined ordering of keys.

Matthew Flaschen
+2  A: 

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.

Kris Jenkins
If the OP does really *want* this, it is not hard to write a collection backed by a TreeSet and a Map. That way you can get the results always in the same order. Now as to how to behave when the Map is modified during iteration is up to the OP but a data structure that is a map where the keys are in an ordered set is definitely doable. (btw I'm more commenting on your answer than on the OP's question).
Webinator
A: 

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
}
binil
A: 

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.

aperkins