The total number of pairs is the summation of ( fi * ( fi - 1 ) ) / 2
for ( Map . Entry < Integer , Integer > i : freq . entrySet ( ) ) { sum += ( ( i . getValue ( ) - 1 ) * i . getValue ( ) ) / 2 ; } return sum ; }