Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find if HashMap contains chosen value and return key

Tags:

java

Is there any way to find if my HashMap<String, String> contains entry ( key,value) with value="x" and to go through all entries sequentially ?

like image 733
Dayanne Avatar asked Mar 08 '11 09:03

Dayanne


3 Answers

HashMap.containsKey()

This is what HashMap is made for in the first place...

(Not sure what you mean by "to go through all entries sequentially", though. There's only 1 entry per key.)


Edit:

Now that you edited the question, the answer is no! :(

If you need that feature, design your own two-way HashMap that stores the location of each value in the other's value (hopefully that made sense), and then use that class. HashMaps aren't designed for this.

like image 198
user541686 Avatar answered Oct 24 '22 08:10

user541686


There is the containsValue() method, but for common implementations this just internally iterates through all values and compares them to the parameter.

like image 36
Paŭlo Ebermann Avatar answered Oct 24 '22 08:10

Paŭlo Ebermann


A common pattern is to use

if(hashMap.containsKey(key)) {
    Object o = hashMap.get(key);

}

however if you know none of the values are null (Many Map collections do not allow null) then you can do the following which is more efficient.

Object o = hashMap.get(key);
if (o != null) {

}

BTW: containsKey is the same as

Set<Key> keys = hashMap.keySet();
boolean containsKey = keys.contains(key);
like image 30
Peter Lawrey Avatar answered Oct 24 '22 09:10

Peter Lawrey