[英]Faster way to find out the key for given value from Map?
我想從HashMap中找出給定值的關鍵,目前我必須通過所有鍵並在地圖中檢查它的值,有更快的方法嗎?
用於執行此操作的備用數據結構將是來自google collections API的BiMap
。
API文檔在這里 。
不,沒有更快的方法(沒有引入其他數據結構)。 如果您需要經常這樣做,請重新考慮您的設計。 也許你想另一個HashMap
的鍵是其他的值HashMap
?
這將是最簡單的方法
private Object getKey(LinkedHashMap lm, int val){
Object[] j = lm.keySet().toArray();
return j[val];
}
這是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");
}
}
如果你看一下HashMap.get(key)方法,你會看到使用
Entry entry = getEntry (key);
為什么getEntry (key)方法是私有的? 它返回所需搜索的鍵和值。 我將通過蠻力使用這種方法,但它是丑陋的解決方案......
下面是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;
}
使用更好的數據結構,如TreeMap,因為搜索效率會更高。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.