Find unique elements in array Java
In Java, an array is a collection of elements of the same data type. An array doesn't restrict us from entering the same or repeated elements in it. So, many times we need to get the distinct elements from the array. In Java, there is more than one way to find unique elements from an array which are as follows:
By using hashmap's key
In Java, the simplest way to get unique elements from the array is by putting all elements of the array into hashmap's key and then print the keySet(). The hashmap contains only unique keys, so it will automatically remove that duplicate element from the hashmap keySet.
Let's take an example to understand how the hashmap's key is used to get the distinct element.
By using nested loop
Another simple approach to getting distinct elements from the given array is by using the nested loop. The inner and outermost loop plays a very important role in this strategy. The outermost loop takes an element one by one from the leftmost side of the array. The innermost loop compares it with the right-side of this element. If it matches, we skip it else, print or store it into another array that contains the distinct element.
Let's take an example to understand how this strategy works in Java:
By using sorting
The solution we have discussed before has O(n2) time complexity, but we have another solution that has less complexity than the previous one. We can get the distinct elements from the array by performing a sorting algorithm. This solution has O(nLogn) time complexity.
In order to get the distinct element from the array, we will first sort the array in ascending or descending order so that each element's occurrence becomes consecutive. After that, we will traverse that sorted array using the loop and skip all the consecutive repeated elements' index.
Let's take an example to understand how we can get the distinct element from the array by using the sorting algorithm.
By using hashing
There is another way to get the distinct element from the array, i.e., hashing. By using the hashing, we can get a distinct element in O(n). We traverse the array from which we want to get the distinct element. We perform traversing from left to right, and in the hash table, we keep the record of the visited element.
Let's implement the code to understand how hashing is used to get the distinct element from the array.
All the above-discussed methods are used to get the distinct elements from the array. All the methods have different time complexity to get the distinct element. All the methods play an important role in different scenarios.