gpt4 book ai didi

java - 从 Java 哈希表中的值中检索键

转载 作者:行者123 更新时间:2023-11-29 05:47:59 25 4
gpt4 key购买 nike

我是 Collection 界的新手,但在我下面的类(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 类型可能是错误的。我建议你把值变成键并制作一个 Map<String, Set<String>>相反

关于java - 从 Java 哈希表中的值中检索键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15094977/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com