开发者

Faster way to find out the key for given value from Map?

I want to find out the key for given value from HashMap, currently I have to go through all keys and check its value in map,开发者_StackOverflow社区 is there a faster way?


An alternate data structure for doing this would be a BiMap from the google collections API.

The API doc is here.


No, there is not a faster way (without introducing other data structures). If you need to do this often, reconsider your design. Maybe you want another HashMap whose keys are the values of the other HashMap?


This would be the simplest way to do this

private Object getKey(LinkedHashMap lm, int val){

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


Here are two related posts on stackoverflow:

  1. Does Java have a HashMap with reverse lookup?
  2. Bi-directional Map in Java?

Some solution hadn't been mentioned yet BidiMap:

The source code is from here:

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


If you look at HashMap.get(key) method you will see a use of

Entry entry = getEntry(key);

Why is getEntry(key) method private?? It returns key and value for desired search. I will use this method by brute force, but it is ugly solution...

Implementation of method in HashMap follows

/**
 * 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;
}


Use a better datastructure, like a TreeMap, as that will be much more efficient to search.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜