Get keys from HashMap in Java

masb picture masb · May 5, 2012 · Viewed 623.2k times · Source

I have a Hashmap in Java like this:

private Map<String, Integer> team1 = new HashMap<String, Integer>();

Then I fill it like this:

team1.put("United", 5);

How can I get the keys? Something like: team1.getKey() to return "United".

Answer

Matteo picture Matteo · May 5, 2012

A HashMap contains more than one key. You can use keySet() to get the set of all keys.

team1.put("foo", 1);
team1.put("bar", 2);

will store 1 with key "foo" and 2 with key "bar". To iterate over all the keys:

for ( String key : team1.keySet() ) {
    System.out.println( key );
}

will print "foo" and "bar".