Count distinct elements in an array | Java program to count all distinct elements in a given array ; First sort the array so that all occurrences become consecutive ; Traverse the sorted array ; Move the index ahead while there are duplicates ; Driver code
import java . util . Arrays ; class GFG { static int countDistinct ( int arr [ ] , int n ) { Arrays . sort ( arr ) ; int res = 0 ; for ( int i = 0 ; i < n ; i ++ ) { while ( i < n - 1 && arr [ i ] == arr [ i + 1 ] ) { i ++ ; } res ++ ; } return res ; } public static void main ( String [ ] args ) { int arr [ ] = { 6 , 10 , 5 , 4 , 9 , 120 , 4 , 6 , 10 } ; int n = arr . length ; System . out . println ( countDistinct ( arr , n ) ) ; } }