我是收藏界的新手,但仍然,在我下面的课程中,我有哈希表,因为我必须选择哈希表,并且我想根据值检索键,下面是我的课程..
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
现在请告知是否有其他更好的方法来实现相同的目标,请告知是否有其他更好的选择。