If current element is different from the previous element i . e . it is appearing for the first time in the current row
if ( mat [ i ] [ j ] != mat [ i ] [ j - 1 ] ) if ( cnt . containsKey ( mat [ i ] [ j ] ) ) { cnt . put ( mat [ i ] [ j ] , cnt . get ( mat [ i ] [ j ] ) + 1 ) ; } else { cnt . put ( mat [ i ] [ j ] , 1 ) ; } } }