HashMap Searching For A Specific Value in Multiple Keys

后端 未结 3 1692
别跟我提以往
别跟我提以往 2021-01-29 10:34

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 check

相关标签:
3条回答
  • 2021-01-29 10:57

    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.

    0 讨论(0)
  • 2021-01-29 11:05

    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

    0 讨论(0)
  • 2021-01-29 11:08

    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.

    0 讨论(0)
提交回复
热议问题