HashMap Searching For A Specific Value in Multiple Keys

浪子不回头ぞ 提交于 2019-12-20 07:58:15

问题


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.


回答1:


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




回答2:


You can have a bi-directional map. E.g. 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.




回答3:


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, i.e. the Map is a Map<String, String>, then @Matt has the simple answer.



来源:https://stackoverflow.com/questions/20381968/hashmap-searching-for-a-specific-value-in-multiple-keys

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!