×

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 Try Keyword

The try block in Java is used to run essential code, such as connection closure, among other things. Whether an exception is resolved or not, the Java try block has...

3 minutes read.

Java SHA256

Definition: In cryptography, SHA is a hash function that takes 20 bytes of input and produces an approximate 40-digit hexadecimal integer as the hash result. Class for Message Digest: Java's MessageDigest Class,...

2 minutes read.

How to Update Java

As we all know that java can be installed in all operating systems like windows, Linux, macOS. We are available with the java 17 and java 18 versions in the...

3 minutes read.

Java Destructors

Before knowing about Java destructors, let us know about constructors. If we understand the concept of the constructor, we can easily understand about destructor and also, we will get an...

3 minutes read.

Java Protected Keyword

An access modifier is a keyword that Java protects. It can be used to constructors, methods, inner classes, and variables. Variables, methods, and constructors that have been marked protected in...

3 minutes read.

Java 9 Interface Private Method

Java 9 provides us the facility to include private methods inside the java interface. In java 8 and earlier versions, we are supposed to use only constant variables and abstract...

3 minutes read.

Java Set Interface

We use set when we don't want to allow duplicate entries. All Set implementations do not allow duplicates. HashSet: This class stores its elements in hash tables. It uses the hashCode()...

3 minutes read.

Difference between String Tokenizer and split Method in Java

Introduction Today, let us understand the difference between String Tokenizer and Split Method. First, let us learn about the String Tokenizer and Split method individually and then know about their differences String...

7 minutes read.

Java Boolean logicalAnd() Method

The logicalAnd() method of Java Boolean class returns the result of implementing logicalAND operation on the specified Boolean operands. Syntax:public static boolean logicalAnd (boolean a, boolean b) Parameters:The parameters ‘a’ and ‘b’...

2 minutes read.

Java Read File to String

There are different ways to deal with forming and examining a text record. This is normal while dealing with various applications. There are different ways to deal with looking at a...

6 minutes read.

String isnullorempty in Java

What do you mean by String? 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.

Array Slicing in Java

Array slicing is a method in Java for obtaining a subarray of a specified array. Assume a[] is an array. It contains eight items indexed from a[0] to a[7].a[] =...

3 minutes read.

Java delete directory

The File classes in Java may symbolize a directory or a file on the system. Inside the java.io package, the Files class is accessible. The File class has several helpful...

2 minutes read.

How to reverse a linked list in java

The process of reversing a linked list in Java will be covered in this section. One of the most common questions in interviews is about reversing a linked list. If...

11 minutes read.

if-else Program in Java

if-else Program in Java The if-else program in Java controls which code snippet will execute. The if-else program is very basic and yet very important. Because it checks how well one...

19 minutes read.

MessageDigest in Java

The compression of mathematical numbers is accomplished using hash functions. In almost every data security application, hash functions are employed. The hashing, often called has values, returns a value called...

3 minutes read.

Java File Extension

A computer file's suffix is called its file extension. It is easily recognized since it appears immediately after a period (.) in the file name. Consider the file Demo.java as an...

3 minutes read.

Normal and Trace of a Matrix in Java

Normal of a matrix The square root of the total squares of each element in a matrix is known as the matrix's normal. Think of the following matrix as an example. Example: [[1,2,3]  ...

3 minutes read.

How to take Array Input in Java

In this tutorial, we will learn about how to take array input in Java. So, before taking inputs let us know what an array is first. Array: An array is a collection...

10 minutes read.

Java Math cos() Method

The cos() method of Math class returns the trigonometric cosine of the specified angle. Syntax: public static double cos(double a) Parameters: The parameter ‘a’ represents an angle measured in radians. Return Value: The cos() method returns...

1 minute read.