Asking for "the first elemet" of a HashMap does not make sense, because the order can (and will, in general) change as elements are added and removed.
This is explained in the documentation for HashMap
"... makes no guarantees as to the order of the map; in particular, it does not guarantee that the order will remain constant over time."
You can test it with the following experiment:
import java.util.HashMap;
public class M {
public static void main(String[] args) {
HashMap<String, Integer> m = new HashMap<String, Integer>();
for (int i=1, p=1; i<100000; i++) {
m.put(""+i, i);
if (i == p) {
p <<= 1; // keys are reordered at power-of-two multiples
System.out.println("at " + p + ": first is now "
+ m.keySet().iterator().next());
}
}
}
}
The output is (JDK 1.7):
at 2: first is now 1
at 4: first is now 2
at 8: first is now 3
at 16: first is now 3
at 32: first is now 15
at 64: first is now 19
at 128: first is now 35
at 256: first is now 35
at 512: first is now 35
at 1024: first is now 338
at 2048: first is now 338
at 4096: first is now 1411
at 8192: first is now 3280
at 16384: first is now 6873
at 32768: first is now 10997
at 65536: first is now 10997
at 131072: first is now 10997
If you require repeatable ordering (= iterating over elements will always give you their order of insertion), you can always use a LinkedHashMap. Beware that they require a bit more memory and are slightly slower than the standard variety.
HashMap, because the concept of "index" is completely meaningless for aHashMap. The currently highest voted answer (and comment) explains this quite clearly. What you are asking for is impossible. If you want a map that you can navigate, use an implementation ofNavigableMap. In addition, what exactly do you mean by "first"? First element you put in to the map? First element in a sorted map?