Reputation: 330
I have the following hashmap, that stores string keys and linked list values
public HashMap<String, LinkedList<String>> wordIndex = new HashMap<>();
My wordIndex contains multiple linked lists that contains the word "algorithms", so I wrote the following code to see if my hashmap is able to find the word "algorithms"
String getWord(String query) { //query=user input in this case algorithms
if(wordIndex.containsValue(query.toLowerCase()))
{
return "hello"; //should return hello if word is found
}
else
{
return "none";
}
}
However it is always returning none, which means it can find the word in the linked list. So what is the correct procedure to traverse through linked Lists inside Hashmaps. I searched but couldn't find any answer.
Also I need to return all the KEYS, containing the query word (in this case "algorithm"). I cant seem to find a function in the hashmap class that can do that(or maybe I saw it but didn't understand it). I am new to hashmaps could you guys please help me out and point me in the right direction.
Upvotes: 0
Views: 1363
Reputation: 21
public boolean containsValue(Object value) {
if (value == null)
return containsNullValue();
Entry[] tab = table;
for (int i = 0; i < tab.length ; i++)
for (Entry e = tab[i] ; e != null ; e = e.next)
if (value.equals(e.value))
return true;
return false;
}
if you look at the containsValue method you will see it uses Entry object equals method for matching and if you look this Entry class equals method objects other than Entry type it returns false. I think the best way is using contains method of linked list while iterating over map for each record
public final boolean equals(Object o) {
if (!(o instanceof Map.Entry))
return false;
Map.Entry e = (Map.Entry)o;
Object k1 = getKey();
Object k2 = e.getKey();
if (k1 == k2 || (k1 != null && k1.equals(k2))) {
Object v1 = getValue();
Object v2 = e.getValue();
if (v1 == v2 || (v1 != null && v1.equals(v2)))
return true;
}
return false;
}
Upvotes: 0
Reputation: 2773
You can't do that. If you want to check if there is the word in any LinkedList in the HashMap, you should do something like :
String getWord(String query) { //query=user input in this case algorithms
for(LinkedList<String> l : wordIndex.values()) {
if(l.contains(query.toLowerCase())) {
return "hello"; //should return hello if word is found
}
}
return "none";
}
Upvotes: 3