Java tutorial
//package com.java2s; import java.util.Map; import java.util.Map.Entry; public class Main { /** * Cosine similarity * * @param map1 * @param map2 * @return sim(map1, map2) = dotProduct / (map1Magnitude * map2Magnitude); */ public static Double calculateCosine(Map<Object, Integer> map1, Map<Object, Integer> map2) { Integer dotProduct = calculateDotProduct(map1, map2); Double map1Magnitude = calculateMagnitude(map1); Double map2Magnitude = calculateMagnitude(map2); Double coefficient = dotProduct / (map1Magnitude * map2Magnitude); return coefficient; } private static Integer calculateDotProduct(Map<Object, Integer> map1, Map<Object, Integer> map2) { Integer sum = 0; for (Entry<Object, Integer> entry1 : map1.entrySet()) { Integer value1 = entry1.getValue(); Integer value2 = map2.get(entry1.getKey()); if (value2 != null) { Integer prod = value1 * value2; sum += prod; } } return sum; } private static Double calculateMagnitude(Map<Object, Integer> map1) { Double sum = 0.0; for (Integer value : map1.values()) { sum += Math.pow(value, 2); } return Math.sqrt(sum); } public static Number getValue(Map<? extends Object, ? extends Number> map, Object key, Class<?> clazz) { Number value = map.get(key); if (value == null) { if (clazz.equals(Double.class)) { value = 0.0; } else { value = 0; } } return value; } }