开发者

Find if HashMap contains chosen value and return key

Is there any way to find if my HashMap<String, String> contains entry ( key,value) with value="x" and to go through all entries seque开发者_JAVA百科ntially ?


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.


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


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);


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.


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜