我是一个收集世界的新手,但仍然在下面的类中,我有散列表,因为我必须选择散列表,并且我想检索下面的值的关键基础是我的课..从Java中哈希表中的值中检索密钥
public class KeyFromValueExample
{
public static void main(String args[])
{
Hashtable table = new Hashtable();
table.put("Sony", "Bravia");
table.put("Samsung", "Galaxy");
table.put("Nokia", "Lumia");
System.out.println("does hash table has Lumia as value : " + table.containsValue("Lumia"));
System.out.println("does hash table Lumia as key : " + table.containsKey("Lumia"));
//finding key corresponding to value in hashtable - one to one mapping
String key= null;
String value="Lumia";
for(Map.Entry entry: table.entrySet()){
if(value.equals(entry.getValue())){
key = entry.getKey();
break; //breaking because its one to one map
}
}
System.out.println("got key from value in hashtable key: "+ key +" value: " + value);
//finding key corresponding to value in hashtable - one to many mapping
table.put("HTC", "Lumia");
Set keys = new HashSet();
for(Map.Entry entry: table.entrySet()){
if(value.equals(entry.getValue())){
keys.add(entry.getKey()); //no break, looping entire hashtable
}
}
System.out.println("keys : " + keys +" corresponding to value in hash table: "+ value);
输出: -
does hash table has Lumia as value : true
does hash table has Lumia as key : false
got key from value in hashtable key: Nokia value: Lumia
keys : [Nokia, HTC] corresponding to value in hash talbe: Lumia
现在请advis是否有其他更好的方法来达到同样的事情,请告知,如果其他更好的选择在那里。
非常感谢你能不能请转换并提前 – user2094103 2013-02-26 17:10:30
张贴到googlebitMap一个我的代码,这将使认识更加清晰,感谢@ user2094103:如Alexander Pogrebnyak表示,“BiMap”仅适用于唯一键和唯一值。您的值有重复... – jlordo 2013-02-26 17:11:34