【问题标题】:Return key for a value found in Hashtable返回在 Hashtable 中找到的值的键
【发布时间】:2018-01-31 10:39:16
【问题描述】:

我知道如何在 Hashtable 中找到对应键的值,但是如何找到附加到特定值的键?我写了一个循环遍历字符串并查找关键字的函数。它做得很快,但我需要返回找到的值(关键字)的键。这是我目前的方法

public void findKeywords(POITextExtractor te, ArrayList<Hashtable<Integer,String>> listOfHashtables, ArrayList<Integer> KeywordsFound) {
    String document = te.getText().toString();
    String[] words = document.split("\\s+");
    int wordsNo = 0;
    int wordsMatched = 0;
    System.out.println("listOfHashtables = " + listOfHashtables);
    for(String word : words) {
        wordsNo++;
        for(Hashtable<Integer, String> hashtable : listOfHashtables) {
            //System.out.println(hashtable + " found in the document:");
            if(hashtable.containsValue(word)) {

                //<RETURN KEY OF THAT VALUE>

                wordsMatched++;
                System.out.println(word);
            }
        }
    }
    System.out.println("Number of words in document = " + wordsNo);
    System.out.println("Number of words matched: " + wordsMatched);
}

【问题讨论】:

  • 顺便说一句,您有什么理由使用Hashtable 而不是HashMap?在现代代码中,后者通常是首选。
  • Jon Skeet 所说的,再加上我觉得这些哈希表应该使用单词作为键,而不是单词作为值。
  • 一些关键点。感谢你们。在此期间,我将更改我的代码。另一方面,HashMaps 是否比 Hashtables 更有效,或者选择一个而不是另一个的原因是什么?
  • 是的,HashTable 更高效,因为 HashtableVector 等仅保留用于 Java 的无限向后兼容策略。
  • @dsafasfsafasfsa are HashMaps more efficient than Hashtables ??自己探索这个对你更有益:)

标签: java arraylist hashtable


【解决方案1】:

containsValue 无论如何都必须遍历哈希表中的所有条目 - 所以只需更改代码即可:

for (Map.Entry<Integer, String> entry : hashtable) {
    if (word.equals(entry.getValue()) {
        // Use entry.getKey() here
    }
}

从问题的描述中我不清楚你的哈希表打算代表什么 - 但至少 不寻常 有一个从整数到字符串的映射。你确定你不想反过来吗?

【讨论】:

  • 如果你对很多单词运行这个函数,它会变得很慢。如果每个散列表包含每个单词一次且仅包含一次(完美双射),那么预先计算将单词映射到整数的反向散列表并使用它来查询单词会更有效。
  • @MarkJeronimus:当然——我怀疑如果我们对一般要求的内容有更多了解,我们会找到各种不同的方法。鉴于我们没有更多上下文,我正在回答专门提出的问题。
猜你喜欢
  • 2017-08-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-23
  • 2019-07-26
相关资源
最近更新 更多