Here we explain how to find distinct elements from an array by avoiding duplicate elements. In the below program we use array of integers int num[], in this array we found distinct elements.

For finding the distinct elements we use the following two ways.

Program: Find distinct elements from an array

public class MyDisticntElements
{
public static void printDistinctElements(int[] arr)
{
for(int i=0;i<arr.length;i++)
{
boolean isDistinct = false;
for(int j=0;j<i;j++)
{
if(arr[i] == arr[j])
{
isDistinct = true;
break;
}
}
if(!isDistinct)
{
System.out.print(arr[i]+" ");
}
}
}
public static void main(String a[])
{
int[] nums = {5,2,7,2,4,7,8,2,3};
MyDisticntElements.printDistinctElements(nums);
}
}

Output: following is the output of the above program which displays the distinct values from an array. Here we use the simple approach for finding distinct elements and avoid duplicate elements from array and display output.

5 2 7 4 8 3
Display distinct elements in an array

Other than this approach or way we can also use hashmap to find the distinct elements. Hashmap is a part of java collections. In a java HashMap class uses a map interface by using the hash table.

There is difference between array and hashmap is that array store elements in ordered manner and access it using index. In a Hashmap we store values in a key/value pair. We can access any value or element by using its key.

In this example we use hashmap. Here we first put all integers in to hashmap’s key and then print keyset outside of the loop.

Program: FIND DISTINCT ELEMENTS FROM AN ARRAY using HASHMAP.

import java.util.HashMap; 
public class ArrayDistinct 
{ 
  
    public static void main(String args[]) 
  
    { 
        int ar[] = { 10, 5, 3, 4, 3, 5, 6 }; 
        HashMap<Integer,Integer> hm = new HashMap<Integer,Integer>(); 
        for (int i = 0; i < ar.length; i++) 
	{ 
            hm.put(ar[i], i); 
        } 
        System.out.println(hm.keySet()); 
  
    } 
  
} 

Output:

[3, 4, 5, 6, 10]

Find distinct elements in an array

There are other articles are available which gives you detailed information about the array like what is array?, How to declare, initialize, instantiate array.

I hope you enjoy this article! If you have any doubt then please feel free to comment me below.

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to Top