Find Unique Elements in Array Java
An array in Java is a grouping of objects that share the same type of data. We are free to enter identical or repeating elements into an array. Therefore, we frequently need to extract the unique elements from of the array. There are several ways to extract distinct features from an array in Java, including the ones listed below:
- by adding each component to the key of the HashMap.
- utilising stacked loops.
- utilising sorting
- Using hashing
An array's distinct elements are all printed, meaning that duplicate items are not printed and just one copy of each element in the array is printed. The following is a case in point.
An array's distinct elements are all printed, meaning that duplicate items are not printed and just one copy of each element in the array is printed. The following is a case in point. A new approach, which will be detailed further below with some example code, contains the answer to the already mentioned issue, Unique Elements Within Array Java.
utilising the HashMap's key
The easiest way to just get distinct features from an array in Java is to put all of the array's elements into the HashMap's value and then output the keySet (). The duplicate element will be immediately removed from of the HashMap keySet because the HashMap only contains unique keys.
To understand better how well the HashMap's value is used to obtain the distinct element, let's look at an example.
Unqelem.java
// importing all the required packages
import java.util.HashMap;
class Unqelem {
// main method starts here
public static void main (String args[])
{
// generate a duplicate elements integer array.
int arr[] = { 10, 3, 5, 3, 9, 22, 4, 3, 1, 5, 6 };
// create a HashMap with integer key value pairs.
HashMap<Integer,Integer> hm = new HashMap<Integer,Integer>();
// pull the array's elements into the HashMap’s key using a for loop.
for (int x = 0; x < arr.length; x++) {
hm.put(arr[x], x);
}
// utilise HashMap. keySet() for using its keySet() method to print all HashMap keys
System.out.println(hm.keySet());
}
}
Output:
[1, 3, 4, 5, 22, 6, 9, 10]
By means of nested loop
The nested loop is another straightforward method for obtaining unique elements from the provided array. In this method, the inner & outermost loops are crucial. The outermost loop pulls each element from the array's leftmost side one at a time. The innermost loop makes a comparison with this element's right side. If it fits, we skip it; if not, we print it or put it in a different array with the unique element.
Implementing two nested loops is a Simple Solution. Starting with the leftmost element, the outer loop selects each element one at a time. If the object exists on the left side of the inner loop, it is verified. If the element is present, it is ignored; otherwise, it is printed. The simple algorithm is implemented in the paragraphs that follow.
To further understand how this tactic functions in Java, let's look at an example:
Unqelem1.java
// importing all the required packages and classes
import java.io.*;
class Unqelem1 {
//main method starts here
public static void main (String[] args)
{
// generate a duplicate elements integer array.
int arr[] = { 10, 3, 5, 3, 9, 22, 4, 3, 1, 5, 6 };
// determine the arr's length.
int size = arr.length;
// make an integer array with several components to store
int[] disarr = new int[20];
// to increase the array index using integer variables
int ind = 0;
// from the leftmost side, the outermost loop will accept each element individually.
for (int x = 0; x < size; x++)
{
int map = 0;
// The innermost loop compares the elements and skips any duplicates.
for (int y = 0; y < x; y++) {
if (arr[x] == arr[y]) {
map = 1;
break;
}
}
// If the element is absent from the disarr, save it or print it.
if (map == 0){
disarr[ind] = arr[x];
ind++;
// increment the value of ind
}
}
// printing the disarr
for (int x = 0; x < ind; x++)
System.out.print( disarr[x] + " ");
}
}
Output:
10 3 5 9 22 4 1 6
By using sorting
We have a different solution that is less difficult than the one we previously mentioned and has O(n2) time complexity. We can use a sorting technique to extract the unique elements from the array. The complexity of this solution is O (nLogn).
The array will first be sorted in order of appearance so each element's appearance becomes sequential before we can extract the separate element from the array. After that, we'll use a loop to iterate through the sorted array while skipping over any consecutively repeated elements' indexes.
To better understand how the sorting method can be used to extract the unique member from the array, let's look at an example.
Unqelem2.java
// importing all the required packages and classes
import java.io.*;
import java .util.*;
// Make an Unqelem2 class to extract unique elements from an array.
class Unqelem2 {
//main method starts here
public static void main (String[] args)
{
// generate a duplicate elements integer array.
int arr[] = { 10, 3, 5, 3, 9, 22, 4, 3, 1, 5, 6 };
// to sort an array with duplicates, perform the sorting
Arrays.sort(arr);
// determine the arr's length sorted array.
int size = arr.length;
// make an integer array with several components to store
int[] disarr = new int[20];
// to increase the array index using integer variables
int ind = 0;
// from the leftmost side, the outermost loop will accept each element individually.
for(int x = 0; x < size; x++){
// Unless there are duplicates ahead, we shall not use the ind.
while (x < size - 1 && arr[x] == arr[x + 1])
x++;
// Keep the specific piece in storage disarr
disarr[ind] = arr[x];
ind++;
}
// printing the disarr
for(int x = 0; x < ind; x++)
System.out.print( disarr[x] + " ");
}
}
Sorting will allow us to finish the task in O(nLogn) time. The concept is straightforward: sort the array first so that every instance of each element is sequential. Once the occurrences start to line up, we can scan the sorted array in O(n) time and print out the individual elements. The notion is put into practise after.
Output:
1 3 4 5 6 9 10 22
Utilizing hashing
There is another method, known as hashing, to extract the unique member from the array. We can obtain a separate element in O via hashing (n). We go through the array in search of the specific element. From left through right, we traverse, and we record the visited elements in the hash table.
Let's put the code into practise to see how hashing works to extract the unique element from of the array.
Unqelem3.java
// importing all the required packages and classes
import java.util.*;
// Make an Unqelem3 class to extract unique elements from an array.
class Unqelem3
{
// main method starts here
public static void main (String[] args)
{
// generate a duplicate elements integer array.
int arr[] = { 10, 3, 5, 3, 9, 22, 4, 3, 1, 5, 6, 10, 6, 5 };
// determine the arr's length in size variable
int size = arr.length;
// Create a HashMap with integer key value pairs.
HashSet<Integer> hs = new HashSet<>();
// pull the array's elements into the HashMap’s key using a for loop.
for (int x = 0; x < size; x++)
{
// Verify if the element is included in the hs. Add it if it isn't already in the hs.
if ( !hs.contains(arr[x]) )
{
hs.add (arr[x]);
}
}
// print a hash set with a unique element.
System.out.print ( hs );
}
}
On average, we could use hashing can solve it in O(n) time. The goal is to go through the provided array form left to right while keeping track of the elements you've seen from a hash table.
Output:
[1, 3, 4, 5, 22, 6, 9, 10]
To extract the unique elements from the array, all of the aforementioned approaches are employed. Each approach takes a varied amount of time to obtain the specific ingredient. In various situations, each strategy is significant.