Find if HashMap contains the selected value and return key

Is there a way to find if my HashMap<String, String> contains a record (key, value) with value = "x" and iterates through all the records sequentially?

+4
source share
6 answers

HashMap.containsKey ()

This is what the HashMap first ...

(Not sure what you mean by the word β€œto go through all the records sequentially,” but only 1 record per key.)


Edit:

Now that you have edited the question, the answer will not be !: (

If you need this function, create your own two-way HashMap , which will store the location of each value in a different value (I hope this makes sense), and then use this class. HashMap not designed for this.

+8
source

There is a containsValue() method, but for regular implementations, it just internally iterates over all the values ​​and compares them with the parameter.

+4
source

A common pattern is to use

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

however, if you know that none of the values ​​is null (many Map collections do not allow null), 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); 
+1
source

Use HashMap.containsKey () to find out if it contains a given key. Use HashMap.keySet () or HashMap.entrySet () to restore a collection of records or values ​​and iterate over them sequentially.

0
source

You may find the information you are looking for, but it will be ineffective:

 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 other answers, you can consider the best data structure for the problem you are trying to solve.

0
source

You might like to use a bidirectional map such as the Google Guava library: http://guava-libraries.googlecode.com/svn/trunk/javadoc/index.html?com/google/common/collect/BiMap.html

0
source

Source: https://habr.com/ru/post/1342778/


All Articles