简体   繁体   中英

How to check if Hashtable contains specific key?

I have a ArrayList<String> and a Hashtable<String, Double> . So when I compare the arraylist with hash table, if the key(string) is found I want to get the value(double) and find the total value at the end when all the arraylist is compared. But it's giving score 0 always.

There is the code

ArrayList<String> Trigram = Trigrams.GenerateTrigrams(extra, 3);

// System.out.print(Trigram);
Hashtable<String, Double> map = readModleFile("Models//EnglishModel.txt");

double score = 0;

for (String temKey : Trigram) {
  if (map.contains(temKey)) {
    Double value = map.get(temKey);
    score = score + value;
  } else {
    score = 0;

  }

}
System.out.print(score);

Your else branch is always resetting the score to 0; the score will always be reset at least once unless the map contains all of the elements of the list. Simply remove the branch.

The second problem is that you are using contains , which checks for a value being present, instead of containsKey , which checks for the presence of a key.

for (String temKey : Trigram) {
  if (map.containsKey(temKey)) {
    Double value = map.get(temKey);
    score = score + value;
  }
}

The code can also be shortened and made more concise using getOrDefault , which will either return the mapping associated with the key or the second argument (default value) if there is no mapping associated with the key.

for (String temKey : Trigram) {
  score += map.getOrDefault(temKey, 0);
}

There are two problems in your code:

  1. Using contains instead of containsKey .
  2. The else block is resetting score to 0 whenever the specified key is not found. Remove the else block.

You can also simplify your code as follows:

The following 4 lines

if (map.containsKey(temKey)) {
    Double value = map.get(temKey);
    score = score + value;
}

can be replaced with just one line

score += map.getOrDefault(temKey, 0);

Remove else - it makes the score zero, every time the key is not present in the map .

If the following does not work

System.out.println(map);     // debug statement
for (String temKey : Trigram) {
  System.out.println("temKey = " + "\"" + temKey + "\""); // debug statement
  if (map.containsKey(temKey)) {
    Double value = map.get(temKey);
    score = score + value;
  } 
}

Then check the Trigram list and the HashTable to ensure the case of the Strings are the same or that they even exist. And make certain you are comparing "word" to "word" and don't have extraneous white space. So you may need to trim white space from the values. And put in some debug statements like the above.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM