Do the following
package com.example;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
/** Computes the similarity between two bags of words.
* 1.0 is most similar, 0.0 is most unsimilar.
*
*/
public class Cosine {
public static double cosine(Collection<String> a, Collection<String> b) {
Map<String,Integer> aa = asBag(a);
Map<String,Integer> bb = asBag(b);
double sum = 0;
for (String word: aa.keySet()) {
if (!bb.containsKey(word)) continue;
sum += aa.get(word) * bb.get(word);
}
return sum / (norm(aa) * norm(bb));
}
private static double norm(Map<String, Integer> bag) {
double sum = 0;
for (int each: bag.values()) sum += each * each;
return Math.sqrt(sum);
}
private static Map<String,Integer> asBag(Collection<String> vector) {
Map<String,Integer> bag = new HashMap<String,Integer>();
for (String word: vector) {
if (!bag.containsKey(word)) bag.put(word,0);
bag.put(word, bag.get(word) + 1);
}
return bag;
}
}
Type inference, anyone?