Java Program to Print All Distinct Elements in Array

Given an array ‘arr’ that may contain duplicate elements and we need to print distinct elements from that array.

In other words, we need to find all the elements from the given array which have exactly occurred once.

Given Input : 

6,6,3,7,2,3,2

Expected output:

7

Java Program to Print All Distinct Elements in an Array

Program:

public class Main {

        public static void main(String[] args) {
            int[] arr = new int[]{6,6,3,7,2,3,2};
            int count;
            boolean flag = false;
            for(int i=0;i<arr.length;i++)
            {
                 count =  1;
                for(int j=0;j<arr.length;j++)
                {
                    if(arr[i] == arr[j] && (i !=j))
                    {
                        ++count;
                        break;
                    }
                }
                if(count==1) {
                    flag = true;

                    System.out.println(arr[i]);
                }

            }
            if(flag == false)
                System.out.println("Nothing is unqiue");

        }

}

Output:

blog 5

Leave a Reply