Count of index pairs with equal elements in an array | Java program to count of index pairs with equal elements in an array . ; A method to return number of pairs with equal values ; Finding frequency of each number . ; Calculating count of pairs with equal values ; Driver code
import java . util . * ; class GFG { public static int countPairs ( int arr [ ] , int n ) { HashMap < Integer , Integer > hm = new HashMap < > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( hm . containsKey ( arr [ i ] ) ) hm . put ( arr [ i ] , hm . get ( arr [ i ] ) + 1 ) ; else hm . put ( arr [ i ] , 1 ) ; } int ans = 0 ; for ( Map . Entry < Integer , Integer > it : hm . entrySet ( ) ) { int count = it . getValue ( ) ; ans += ( count * ( count - 1 ) ) / 2 ; } return ans ; } public static void main ( String [ ] args ) { int arr [ ] = new int [ ] { 1 , 2 , 3 , 1 } ; System . out . println ( countPairs ( arr , arr . length ) ) ; } }