×

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.


Related Topics

Java Integer rotateRight() method

The rotateRight() method of Java Integer class returns the value obtained by rotating the  2’s complement binary representation of the given integer value right by the specified number of bits. Syntax public...

1 minute read.

How to check version of java in Linux

Java is one of the most famous and thoroughly utilized programming tongues from one side of the world to the other. On the off chance that you are a Java...

2 minutes read.

Reverse a String in Java

Reversing a string means that if we have a string called “what is your name”, the reversed format is “eman ruoy si tahw”. Reversing a string involves totally flipping the...

3 minutes read.

Java Math min() Method

The min() method of Math class returns the smaller of two arguments. The arguments can be of double, float, int or long data type. Syntax: public static double min (double a, double...

2 minutes read.

Java String compareTo() Method

compareTo() method is used to compare the two specified Strings based on the alphabetical order(lexicographical order) of their characters.It returns positive number ,negative number or 0 Syntax: public int compareTo(String anotherString) Parameters: anotherString: the...

2 minutes read.

Anagram Program in Java using String

Anagram Program in Java Anagrams are those words that are generated by rearrangement of the letters of another phrase or word. Usually, while doing the rearrangement, the original letters are used...

8 minutes read.

Order of Execution of Constructors in Java Inheritance

Constructor in Java There are several distinctions between a method and a function object() in Java. The name of the function object()  is identical to the class name. There is no...

4 minutes read.

Interleaving string in Java

If the string Str3 contains all of the characters from Str1 and Str2, it is considered interleaving Str1 and Str2. Keep in mind that the order of all characters in...

5 minutes read.

Exception Handling Program in Java

Exception Handling Program in Java Exception means something that is abnormal. In Java, an exception is treated as a problem that disrupts the normal flow of the program. An exception leads...

7 minutes read.

Java Console

If there is a character-based console device connected to the active Java virtual machine, it can be accessed using methods provided by the Java.io.Console class. JDK 6 adds the Console...

3 minutes read.

Java Garbage Collection Interview Questions

One of the key areas of Java is garbage collection. Garbage collection enables apps to manage memory automatically. Interviewers frequently ask inquiries about garbage collection. Q1: What is the purpose of...

6 minutes read.

Java RMI

What is RMI in Java? A framework for developing distributed Java applications is provided by the RMI (Remote Method Invocation) API. An object can call methods on an object running in...

4 minutes read.

Java Technologies List

Introducing Java technology is not necessary. Everyone across the globe is still in awe of Java's incredible capabilities for developing mobile apps and websites. Of course, you can be persuaded...

8 minutes read.

ArrayList VS Linked List

ArrayList VS Linked List Both the ArrayList and LinkedList implements the List interface, and they have some differences as well as some similarities between them. The internal working and performance of both vary significantly. Let’s...

7 minutes read.

Model Class in Java

In this section, we will be acknowledged about the model class in Java, its purpose and its uses. Also, we will learn how is this created and leveraged in java. Model...

4 minutes read.

Cyclic Barrier in Java

Programmers often find it challenging to run multiple threads simultaneously. Java introduces the idea of concurrency, which enables us to run many threads concurrently, making this work simpler. Concurrent programming...

6 minutes read.

Stone Game in Java

In this tutorial, we will learn to design a stone game in Java. First of all, we will understand what is this game all about. We will grasp it through...

9 minutes read.

Java Integer max() method

The max() method of Integer class returns the greater of two int values. It returns the same result as by calling Math.max. Syntax public static int max(int a, int b) Parameters The parameters ‘a’...

2 minutes read.

Java Pi

What is Pi? There are many formulas in geometry that employ the Pi constant to calculate things like circumference, area, and volume. A circle's circumference divided by its diameter yields a...

3 minutes read.

Difference between String, StringBuffer and StringBuilder in java

What is a string in Java? Strings are a collection of characters that are commonly used in Java programming. Strings are regarded as objects in the Java programming language. “String” is a...

4 minutes read.