javahashmapkeyset

Hashmap keySet() returns the value instead of the key


Here is my method.In the hashmap I have pairs of Country - Capital(Russia - Moscow) for Europe.However, it keeps returning me the value(the capital) instead of the key(the country).I tested my hashmap and it is in the correct order.

Map<String, String> europe1 = new HashMap<String, String>()

public String randomCountry(Map theMap)
{
  Random generator = new Random();
  List<String> keys = new ArrayList<String>(theMap.keySet());
  String randomKey = keys.get(generator.nextInt(keys.size()));
  Object theKeyValue = (String )theMap.get(randomKey);

  System.out.println(theKeyValue);
  return (String) theKeyValue;  
}

If I do this:

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

I get my countries printed.

Any ideas why my method does not work as expected?


Solution

  • You are fetching the value here :

    Object theKeyValue = (String )theMap.get(randomKey);
    

    If you want randomCountry to return the key, you should return randomKey instead of theKeyValue.