×

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

Thread Scheduler in java

Scheduling: it is defined as the execution of multiple threads on a single CPU in some order is called scheduling. Preemptive-priority scheduling: This algorithm schedules threads based on their priority relative to other...

11 minutes read.

Java Future Example

Future is an interface in the Java language that is a part of  java.util.concurrent package. It serves as a symbol for the output of an asynchronous computation. The interface offers ways to determine whether a computation has finished,  wait for it to finish, and receive its result. Once the task or calculation is finished, it cannot be undone. A Future interface offers ways to determine whether the computation is finished, to wait for it to finish, and to receive the computation's results. When the computation...

3 minutes read.

Heap Sort in Java

Heap Sort in JavaHeap sort in Java uses the data structure binary heap, min-heap, or max heap to do the sorting of elements. Since min-heap always gives the minimum element first,...

8 minutes read.

Difference between Abstract Class and Interface

There is a similarity between abstract class and interface is that we cannot create objects for both of them. But irrespective of this, there are some differences between them, let’s...

2 minutes read.

How to Convert String to Date in Java

How to Convert String to Date in java You can convert String to Date in Java by using the parse() method. There are two classes which have parse() method namely, DateFormat and SimpleDateFormat classes....

2 minutes read.

Types of Logical Operators in Java

In this tutorial, we are going to study logical operators. A logical operator is an operator that accomplishes a logical operation that is to connect two or more operations. These...

5 minutes read.

Sum of digits in string in java

To find the sum of all digits in a string, you need to traverse through the string one by one character; if the character is an integer, you need to...

2 minutes read.

Bad Operand types for Binary Operator Java

We will discuss how to handle issues in bad operand types for binary operator &, bad operand types for binary operator &&, bad operand types for binary operator ==, and...

4 minutes read.

Java String trim() method

Java String trim() method returns String after eliminating leading and trailing spaces. Note:- Java String trim() method doesn't trim or omit middle spaces. Syntax: public String trim() Returns: It returns string with omitted leading and...

2 minutes read.

How to Split String by Comma in Java

strsplit() technique permits you to break a string given the explicit Java string delimiter. The Java string split property is frequently a space or a comma(,) that you want to...

7 minutes read.

Java BLOB

The two data types used in Java to store binary and big-character objects are BLOB and CLOB. In contrast to other types of data like float, int, double, etc., it...

4 minutes read.

Fibonacci Series Program in Java

Fibonacci Series Program in Java using Recursion Fibonacci series is a series whose every term is comprised of adding its previous two terms, barring the first two terms 0 and 1....

3 minutes read.

Fall through in Java

In this article, you will be acknowledged about the fall through condition in Java along with an example program. Fall through It is a situation where there isn't a break statement in...

3 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.

Converting Long to Date in Java

What Long and Date are in Java and how are they implemented in the Java programming language are the topics of this article. Additionally, we'll go into great detail on...

4 minutes read.

Java Math exp() Method

The exp() method of Math class returns Euler’s number(e) raised to the power of a double value. Syntax: public static double exp(double a) Parameters: The parameter ‘a’ represents the exponent e. Return Value: The exp ()...

2 minutes read.

Java Default Keyword

The Default keyword in java programming language is used as access modifier.If any of the variable or the constructor or the methods or the classes are not assigned with the...

3 minutes read.

How to Create a Package in Java?

For the most part, how to create a package in Java generally, a package is defined as a collection of relevant or irrelevant items together in a very major way....

7 minutes read.

Addition Program in Java

Addition Program in Java We can perform the addition (sum) of two or more numbers by using the arithmetic operator (+). To write an addition program in Java, one must understand...

3 minutes read.

Shopping Bill in Java

Java Shopping Bill Here in this program, we are about to create a JAVA class called Products which will have some properties or attributes like prod_name (Product Name ), qty (quantity),...

4 minutes read.