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 ?

- 54,432
- 29
- 203
- 199

- 1,385
- 5
- 15
- 12
-
1Please take a look into Map interface first – Petro Semeniuk Mar 08 '11 at 09:29
-
2If you change your question to mean the opposite, you should somehow mention that in your edited question or all the existing answers will look quite out-of-place. – Joachim Sauer Mar 08 '11 at 09:40
-
[Possible duplicate: Detailed explanation given ][1] [1]: http://stackoverflow.com/questions/1383797/java-hashmap-how-to-get-key-from-value – cryptickp Jul 30 '13 at 16:12
6 Answers
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. HashMap
s aren't designed for this.

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

- 73,284
- 20
- 146
- 210
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);

- 525,659
- 79
- 751
- 1,130
Use HashMap.containsKey() to know if it contains a given key. Use HashMap.keySet() or HashMap.entrySet() to retreive the collection of entries or values and iterate sequentially on it.

- 5,509
- 3
- 31
- 51
You could find the information you are looking for, but it would be inefficient:
Object key;
Object val;
HashMap hm = new HashMap();
for (Iterator iter = hm.entrySet().iterator(); iter.hasNext();) {
Map.Entry e = (Map.Entry) iter.next();
if (key.equals(e.getKey()) && val.equals(e.getValue())) {
// do something
}
}
As suggested in some of the other answers, you might consider a better data structure for the problem you are trying to solve.

- 21
- 1
You might like to consider using a bidirectional map, such as the one in Google's Guava library: http://guava-libraries.googlecode.com/svn/trunk/javadoc/index.html?com/google/common/collect/BiMap.html