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);
There are two problems in your code:
contains
instead of containsKey
.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);