我是集合世界的新手,但是,在我下面的类(class)中,我有哈希表,因为我必须选择哈希表,并且我想检索值的关键基础,下面是我的类(class)..
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
现在请告知是否有其他更好的方法来实现相同的目标,请告知是否有其他更好的替代方案。
最佳答案
这看起来很明显它对我做了什么。我不确定是否有更有效的方法,但也许如果您需要定期查找值来查找键,那么您使用的映射类型是错误的。我建议您将值转换为键并制作 Map<String, Set<String>>
相反
关于java - Java中从哈希表的值中检索键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15094977/