简体   繁体   中英

Get Key from a specified Value in HashMap

I have a HashMap "stateCityMap" which is a Map>. the Keys are the States ie Goa,Kerala etc and the Values are the Cities ie Panjim,Margao etc. I want to Check if a particular city is present in the HashMap, eg.Margao and give the corresponding key of that value as the result..but everytime i ran the below code.it performs the else part(when the city is not present in the HashMAp). city :- is the name of the city I pass to this function

Code:

  public String getState(Map<String, List<String>> stateCityMap, String city) throws CityNotFoundException {


    HashMap<String, List<String>> g = new HashMap<String, List<String>>(stateCityMap);

    if(g.containsValue(city)){

        System.out.println("State:- " +g.get(city));

    }
    else {
        throw new CityNotFoundException("City Not Found");
        }

    return null;
}

Why is it doing that? why am I getting the wrong result?

It's not efficient, but you need to scan through each list in the map:

public String getState(Map<String, List<String>> stateCityMap, String city) throws CityNotFoundException {
    for (Map.Entry<String, List<String>> entry : stateCityMap.entrySet()) {
        if (entry.getValue().contains(city)) {
            return entry.getKey();
        }
    }

    throw new CityNotFoundException("City Not Found");
}

containsValue method returns true if the map maps one or more keys to the specified value.

In your case type of value is List, but you are calling containsValue method by passing String. So it will always returns false.

Since your value type is List, you will end up iterating all keys and all values to find if a city exists in any of the lists.

Better is to maintain two maps. Challenge will be to make sure that both maps always get updated (insert, delete, update) correctly.

Hope that helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM