Java 在HashTable中找到Key的方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/590327/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 16:35:53  来源:igfitidea点击:

Method to find Key in HashTable

javahashtableloops

提问by Amorpheus

I'm trying to create a method which iterates through a hashtable and returns the key as a string, whats the best way to go about this?

我正在尝试创建一个方法,它遍历哈希表并将键作为字符串返回,最好的方法是什么?

EDIT: copied from comment

编辑:从评论中复制

Sorry if I didn't make it more clear, I'm trying to do this in Java. I've created a test class

抱歉,如果我没有说得更清楚,我正在尝试在 Java 中执行此操作。我创建了一个测试类

public void runprog() {
    hashMap.put("Butter", 50);
    hashMap.put("Beans", 40);
    for (Object o: hashMap.entrySet() ) {
        Map.Entry entry = (Map.Entry) o;
        System.out.println(entry.getKey() + " " + entry.getValue());
    }
}

it outputs

它输出

Butter 50
Beans 40

I've created a method which looks for a Key and returns the value

我创建了一个查找 Key 并返回值的方法

public Object findValue(String Name){
    for (Object o: hashMap.entrySet()) {
        Map.Entry entry = (Map.Entry) o;
        return entry.getValue();
    }
    return null;
}

when I look for Butter it returns 50 when i look for Beans it returns 50

当我寻找 Butter 时它返回 50 当我寻找 Beans 时它返回 50

回答by Aaron Maenpaa

Set up:

设置:

    final Object sentinal = new Object();


    Map<String, Object> map = new HashMap<String, Object>(){{
        put("key1", new Object());
        put("key2", sentinal);
    }};

Given a key, find a value (lookup):

给定一个键,找到一个值(查找):

    System.out.println(map.get("key2") == sentinal);

Given a value, find it's key (reverse lookup):

给定一个值,找到它的键(反向查找):

    for(Map.Entry<String, Object> entry : map.entrySet()){
        if(entry.getValue() == sentinal){
            System.out.println(entry.getKey());
        }
    }

... though, if I have to do regular reverse lookups, I generally build a reverse map:

...不过,如果我必须定期进行反向查找,我通常会构建一个反向映射:

    Map<Object, String> reverse = new HashMap<Object, String>();
    for(Map.Entry<String, Object> entry : map.entrySet()){
        reverse.put(entry.getValue(), entry.getKey());
    }
    System.out.println(reverse.get(sentinal));

回答by Amorpheus

Sorry if I didn't make it more clear, I'm trying to do this in Java. I've created a test class

抱歉,如果我没有说得更清楚,我正在尝试在 Java 中执行此操作。我创建了一个测试类

    public void runprog() {
    hashMap.put("Butter", 50);
    hashMap.put("Beans", 40);
    for (Object o: hashMap.entrySet() ) {
        Map.Entry entry = (Map.Entry) o;
        System.out.println(entry.getKey() + " " + entry.getValue());
    }
}

it outputs

它输出

Butter 50
Beans 40

I've created a method which looks for a Key and returns the value

我创建了一个查找 Key 并返回值的方法

    public Object findValue(String Name){
    for (Object o: hashMap.entrySet()) {
        Map.Entry entry = (Map.Entry) o;
        return entry.getValue();
    }
    return null;
}

when I look for Butter it returns 50 when i look for Beans it returns 50

当我寻找 Butter 时它返回 50 当我寻找 Beans 时它返回 50

回答by basszero

Seems like homework given the example data ("Butter", "Beans")...

鉴于示例数据(“Butter”,“Beans”),这似乎是家庭作业......

In your example, findValue returns the FIRST KEY in the map/table everytime. You're not even using the key (Name) which you pased in. Here is an example that fixes your problem, thought you're using maps in all the wrong way.

在您的示例中, findValue 每次都返回地图/表中的第一个键。您甚至没有使用您输入的密钥(名称)。这是一个解决您问题的示例,您认为您以错误的方式使用地图。

a better way to do this:

一个更好的方法来做到这一点:

// assume Name is your key, ex. "Butter" 
// No need to iterate since maps are designed for lookup
Object value = map.get(Name);

your example, fixed:

你的例子,固定:

public Object findValue(String Name){
    for (Object o: hashMap.entrySet()) {
        Map.Entry entry = (Map.Entry) o;

        // THIS IS THE IMPORTANT LINE
        if(entry.getKey().equals(Name))
        {
            return entry.getValue();
        }
    }
    return null;
}

回答by Zarkonnen

Looking at your second snippet of code, you're not actually using the Name parameter anywhere. So what's happening is that the first time around the loop, the entry's value is returned - and the first value happens to be 50.

查看您的第二段代码,您实际上并未在任何地方使用 Name 参数。所以发生的事情是第一次循环时,返回条目的值 - 第一个值恰好是 50。

You need to check whether the key of the entry actually equals the name you're looking for...

您需要检查条目的键是否实际上等于您要查找的名称...

回答by user772266

Using for loop to get key by value is not time effecient!! and you don't benefit from HashTable.

使用 for 循环按值获取键是不省时的!!并且您不会从 HashTable 中受益。

So since you want to use hashtable for straight and reverse retrival you may use two hashtables. Table1 (key, value) Table2 (value, key)

因此,由于您想使用哈希表进行直接和反向检索,您可以使用两个哈希表。表1(键,值) 表2(值,键)

//Table1
hashtable1.put("Butter", 50);
hashtable1.put("Beans", 40);

//Table2
hashtable2.put(50, "Butter");
hashtable2.put(40, "Beans");

//Retrieving by key
System.out.println(hashtable1.get(50));

//Retrieving by value
System.out.println(hashtable2.get("Butter"));

Output

输出



Butter

牛油

50

50