简体   繁体   中英

HashMap Searching For A Specific Value in Multiple Keys

I'm checking to see if a key in my HashMap exists, if it does, I also want to check to see if any other keys have a value with the same name as that of the original key I checked for or not.

For example I have this.

System.out.println("What course do you want to search?");
    String searchcourse = input.nextLine();
boolean coursefound = false;

if(hashmap.containsKey(searchcourse) == true){
    coursefound = true;
        }

This checks to see if the key exists in my hashmap, but now I need to check every single key's values for a specific value, in this case the string searchcourse.

Usually I would use a basic for loop to iterate through something like this, but it doesn't work with HashMaps. My values are also stored in a String ArrayList, if that helps.

You will want to look at each entry in the HashMap. This loop should check the contents of the ArrayList for your searchcourse and print out the key that contained the value.

for (Map.Entry<String,ArrayList> entries : hashmap.entrySet()) {
    if (entries.getValue().contains(searchcourse)) {
        System.out.println(entries.getKey() + " contains " + searchcourse);
    }
}

Here are the relevant javadocs:

Map.Entry

HashMap entrySet method

ArrayList contains method

You can have a bi-directional map. Eg you can have a Map<Value, Set<Key>> or MultiMap for the values to keys or you can use a bi-directional map which is planned to be added to Guava.

As I understand your question, the values in your Map are List<String> . That is, your Map is declares as Map<String, List<String>> . If so:

for (List<String> listOfStrings : myMap.values()) [
  if (listOfStrings .contains(searchcourse) {
    // do something
  }
}

If the values are just Strings, ie the Map is a Map<String, String> , then @Matt has the simple answer.

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