2013-02-26 67 views
1

我是一个收集世界的新手,但仍然在下面的类中,我有散列表,因为我必须选择散列表,并且我想检索下面的值的关键基础是我的课..从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是否有其他更好的方法来达到同样的事情,请告知,如果其他更好的选择在那里。

回答

1

如果您的地图有两个独特的键和值,可以考虑使用BIMAP番石榴集合 - >http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/collect/BiMap.html

与该库,你可以使用简单的containsKeycontainsValue测试。

+0

非常感谢你能不能请转换并提前 – user2094103 2013-02-26 17:10:30

+0

张贴到googlebitMap一个我的代码,这将使认识更加清晰,感谢@ user2094103:如Alexander Pogrebnyak表示,“BiMap”仅适用于唯一键和唯一值。您的值有重复... – jlordo 2013-02-26 17:11:34

0

我不知道这是你想要的,但你为什么不反转你的键和值?所以,你可以使用

table.put("Lumia", new List<String>("HTC", "Nokia")); 

类似的东西,如果以上是合法的。

2

这看起来很明显,它对我做了什么。我不确定是否有更有效的方法来做这件事,但是如果你需要查找值来定期查找键,那么你使用的地图类型是错误的。我建议你把值插入钥匙,并作出Map<String, Set<String>>代替

+0

非常感谢您请转换并发布代码 – user2094103 2013-02-26 17:11:54

0
Is there a way to find the key of a particular value in HashTable without iterator?? 
like String getvalue(key); ?? 

for(Map.Entry entry: table.entrySet()){ 
      if(value.equals(entry.getValue())){ 
       keys.add(entry.getKey()); //no break, looping entire hashtable 
      } 
     }