我想从HashMap中找出给定值的关键,目前我必须通过所有键并在地图中检查它的值,有更快的方法吗?
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:
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;
}
使用更好的数据结构,如TreeMap,因为搜索效率会更高。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.