Skip to content
Advertisement

Get keys from HashMap in Java

I have a Hashmap in Java like this:

JavaScript

Then I fill it like this:

JavaScript

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

Advertisement

Answer

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

JavaScript

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

JavaScript

will print "foo" and "bar".

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement