Calculate Cosine similarity between Multisets
This is pretty good, but two things come immediately to mind:


Declare variables closest to where they're being used. Declare dotProduct, magnitudeA, and magnitudeB right above your loop.
Don't reassign method arguments. That's really confusing six months down the road. In this case, use a helper method which takes the larger and smaller sets in a specific order.


Example:

import static java.lang.Math.sqrt;

/**
 * [Excluded for brevity]
 *
 * @param &lt;T&gt;
 * type of the token
 */
public final class CosineSimilarity&lt;T&gt; implements MultisetMetric&lt;T&gt; {

    @Override
    public float compare(final Multiset&lt;T&gt; a, final Multiset&lt;T&gt; b) {

        if (a.isEmpty() &amp;&amp; b.isEmpty()) {
            return 1.0f;
        }

        if (a.isEmpty() || b.isEmpty()) {
            return 0.0f;
        }

        if (a.size() &gt;= b.size()) {
            return this.determineSimilarity(a, b);
        } else {
            return this.determineSimilarity(b, a);
        }
    }

    private float determineSimilarity(final Multiset&lt;T&gt; largerSet, final Multiset&lt;T&gt; smallerSet) {
        float dotProduct = 0;
        float magnitudeA = 0;
        float magnitudeB = 0;

        for (final T entry : union(largerSet, smallerSet).elementSet()) {
            final float aCount = largerSet.count(entry);
            final float bCount = smallerSet.count(entry);

            dotProduct += aCount * bCount;
            magnitudeA += aCount * aCount;
            magnitudeB += bCount * bCount;
        }

        // a·b / (||a|| * ||b||)
        return (float) (dotProduct / (sqrt(magnitudeA) * sqrt(magnitudeB)));
    }

    @Override
    public String toString() {
        return "CosineSimilarity";
    }
}