Search code examples
javacollectionstreemap

Fetching all keys for unique value in treemap in JAVA


I have a treemap which has countries as values and corresponding states as keys such that keys are unique and values are duplicate. I want to fetch all keys for a unique value (i.e. I want to fetch all the states of a country by passing that particular country). How do I do that? Let me know if I need to provide any other information.


Solution

  • Here is some code that will hopefully get you going. One observation from your post is that you cannot have more than one value for a given key in a Map. The value would need to be a list or another object type that can hold multiple values.

    String search = "Mexico";
    
    // create our TreeMap
    Map<String, String> stateMap = new TreeMap();
    stateMap.put("CO", "USA");
    stateMap.put("Ontario", "Canada");
    stateMap.put("Chiapas", "Mexico");
    stateMap.put("Chihuahua", "Mexico");
    stateMap.put("TX", "USA");
    stateMap.put("GA", "USA");
    
    // HashSet will store the unique list of states found in the search country
    Set<String> results = new HashSet();
    
    // iterate over the source TreeMap looking for the country to match the search string
    for (String state : stateMap.keySet()) {
       String country = stateMap.get(state);
       if (country.equals(search)) {
          results.add(state);
       }
    }
    
    // iterate through the results set and print each state for the search country
    results.forEach(state -> System.out.println(state));