A faster way to find out the key for a given value from the map?

I want to find out the key for a given value from HashMap, currently I need to go through all the keys and check its value on the map, is there a faster way?

+3
source share
6 answers

No, there is no faster way (without introducing other data structures). If you need to do this often, rethink your design. Perhaps you need another one HashMapwhose keys are the values ​​of the other HashMap?

+6
source

An alternative data structure for this would be BiMapfrom the google collections API.

The API document is here .

+8
source

private Object getKey(LinkedHashMap lm, int val){

    Object[] j = lm.keySet().toArray();
    return j[val];
}
+2

stackoverflow:

BidiMap:

:

package com.discursive.jccook.collections.bidi;
import org.apache.commons.collections.BidiMap;
import org.apache.commons.collections.bidimap.DualHashBidiMap;
public class BidiMapExample {
    private BidiMap countryCodes = new DualHashBidiMap( );
    public static void main(String[] args) {
        BidiMapExample example = new BidiMapExample( );
        example.start( );
    }

    private void start( ) {
        populateCountryCodes( );

        String countryName = (String) countryCodes.get( "tr" );
        System.out.println( "Country Name for code 'tr': " + countryName );
        String countryCode = 
            (String) countryCodes.inverseBidiMap( ).get("Uruguay");
        System.out.println( "Country Code for name 'Uruguay': " + countryCode );

        countryCode = (String) countryCodes.getKey("Ukraine");
        System.out.println( "Country Code for name 'Ukraine': " + countryCode );
    }

    private void populateCountryCodes( ) {
        countryCodes.put("to","Tonga");
        countryCodes.put("tr","Turkey");
        countryCodes.put("tv","Tuvalu");
        countryCodes.put("tz","Tanzania");
        countryCodes.put("ua","Ukraine");
        countryCodes.put("ug","Uganda");
        countryCodes.put("uk","United Kingdom");
        countryCodes.put("um","USA Minor Outlying Islands");
        countryCodes.put("us","United States");
        countryCodes.put("uy","Uruguay");
    }
}
+1

HashMap.get(key),

= getEntry ();

getEntry () private?? . , ...

HashMap

/**
 * Returns the entry associated with the specified key in the
 * HashMap.  Returns null if the HashMap contains no mapping
 * for the key.
 */
final Entry<K,V> getEntry(Object key) {
    int hash = (key == null) ? 0 : hash(key);
    for (Entry<K,V> e = table[indexFor(hash, table.length)];
         e != null;
         e = e.next) {
        Object k;
        if (e.hash == hash &&
            ((k = e.key) == key || (key != null && key.equals(k))))
            return e;
    }
    return null;
}
-1

, ​​ TreeMap, .

-2
source

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


All Articles