Count of index pairs with equal elements in an array | Set 2 | Java program for the above approach ; Function that count the pairs having same elements in the array arr [ ] ; Hash map to keep track of occurences of elements ; Traverse the array arr [ ] ; Check if occurence of arr [ i ] > 0 add count [ arr [ i ] ] to answer ; Return the result ; Driver Code ; Given array arr [ ] ; Function call
import java . util . * ; class GFG { static int countPairs ( int arr [ ] , int n ) { int ans = 0 ; HashMap < Integer , Integer > count = new HashMap < > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( count . containsKey ( arr [ i ] ) ) { ans += count . get ( arr [ i ] ) ; count . put ( arr [ i ] , count . get ( arr [ i ] ) + 1 ) ; } else { count . put ( arr [ i ] , 1 ) ; } } return ans ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 2 , 1 , 1 } ; int N = arr . length ; System . out . print ( countPairs ( arr , N ) ) ; } }