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

标签 java collections dictionary hashtable

我是集合世界的新手,但是,在我下面的类(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/

相关文章:

java - System.getProperty ("java.version")返回 Null

r - Shiny 传单 map 上的自定义标记

java - 如何解析Envelope.Payload.Data的protobuf数据?

java - 如果我们在父列表中添加元素,为什么 JDK 会向 UnmodifyableList 添加一个元素

java - 集合随机播放方法具有空对象

c# - 检查两个集合是否相等

ios - 在具有字典作为“值”的字典中追加和更新

dictionary - ASP.Net MVC 4 - Controller 操作中的字典参数

java - 使用 Gson 解析 JSON。没有键的困难 JSON 结构

java - 如何检测 MainActivity 是由应用程序启动启动的,还是由另一个 Activity 的 Intent 启动的?