我知道如何在哈希表中查找相应键的值,但是如何查找附加到特定值的键?我编写了一个循环遍历字符串并查找关键字的函数。它很快就能做到这一点,但我需要返回找到的值(关键字)的键。这是我到目前为止的方法
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);
}
最佳答案
containsValue
无论如何都必须迭代哈希表中的所有条目 - 因此只需更改您的代码即可做到这一点:
for (Map.Entry<Integer, String> entry : hashtable) {
if (word.equals(entry.getValue()) {
// Use entry.getKey() here
}
}
从问题的描述中我不清楚你的哈希表打算表示什么 - 但至少有一个从整数到字符串的映射是不寻常的。您确定不希望反过来吗?
关于java - 返回在哈希表中找到的值的键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48540086/