Reputation: 101
I know how to find a value for a corresponding key in Hashtable but how do I find what key is attached to a specific value? I wrote a function that loops through a String and finds keywords. It does that pretty quickly but I need to return key of that value(keyword) found. This is my method so far
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);
}
Upvotes: 0
Views: 1620
Reputation: 1500835
containsValue
has to iterate over all the entries in the hash table anyway - so just change your code so that you do that:
for (Map.Entry<Integer, String> entry : hashtable) {
if (word.equals(entry.getValue()) {
// Use entry.getKey() here
}
}
It's not clear to me from the description of the question what your hash tables are intending to represent - but it's at least unusual to have a map from integer to string. Are you sure you don't want it the other way round?
Upvotes: 2