How to Remove Duplicates from Array Java | DataTrained

Varun Yadav Avatar

Introduction to Remove Duplicates From Array Java

Do you know how to remove duplicates from array java? Java is implemented by 3.9% of all websites that employ a server-side programming language that we are aware of. Regardless of what programming language you work with. While dealing with arrays you’re likely to encounter data and specifically duplicates, that you would wish, getting rid off. This blog is going to help you to remove duplicates from array Java. We would have a look at 3 distinct approaches to remove duplicates from array Java. It is to be mentioned that one must assess if the array is sorted or not and then go forward with the subsequent stage of getting rid of duplicates.

Also Read : Multithreading In Java

What is an Array?

Before getting to remove duplicates from array Java, it is important that we learn what Array is. An array is a compilation of things kept at contiguous memory areas. The concept is to store several items of the same category collectively. This will make it much easier to figure out the position of every element by merely attaching an offset to a base value, i.e., the memory area of the first element of your array (generally denoted through the title of the array). The base value is index zero and the distinction between the 2 indexes is the offset.

For simplicity and ease of learning to remove duplicates from array Java, we can think of an array to be a fleet of stairs wherein on every step a value is placed (let’s think of one of your friends). In this case, you can determine the spot of any of your friends by merely being aware of the count of the step they’re on. Always remember, the location of the following index relies upon the data type we use.

Now we can move forward to remove

The above-mentioned image could be looked over as a top-level perspective of a staircase at which you’re at the base of the staircase. Every component could be exclusively identified by its index in the array (in an equivalent manner as you can determine your friends by the step on which they had been on in the aforementioned example).

What is JAVA?

Java is a general-purpose, object-oriented programming language. It is based on classes that are designed to have fewer implementation requirements. It is an application formation platform on a PC. Java is quick, secure, and dependable. It’s commonly used in laptops, data centers, game consoles, scientific supercomputers, cell phones, and other places to develop Java applications. It is important to know what is Java before getting to remove duplicates from array Java.

Java Arrays

Java Arrays

Java array is an object which consists of elements of a comparable data type. Furthermore, The components of an array are kept in a contiguous memory spot. It’s a data structure in which we store identical elements. We can stash just a fixed set of components in a Java array. An individual must be well learnt about the Java arrays before moving on to learning to remove duplicates from array Java. 

Arrays in Java are index-based, the initial element of the array is kept on the 0th index, the 2nd element is saved on the 1st index, and so forth. In contrast to C/C++, we can get the length of the array by making use of the length member. In C/C++, we have to work with the size of operator.

In Java, an array is an object associated with a dynamically produced class. Java array inherits the Object class and also implements the Serializable and Cloneable interfaces. We can keep primitive values or objects within an array present in Java. Like C/C++, we can additionally produce individual dimensional or perhaps multidimensional arrays within Java. Furthermore, Java offers the characteristic of anonymous arrays which is just not available in C/C++. Now we can move forward to remove duplicates from array Java.

Memory Location

Advantages

  • Code Optimization: It will improve the code, allowing us to access and sort data more efficiently.
  • Random Access: We can get any data placed at an index location using random access.

Disadvantages

  • Size Limit: We can keep solely the fixed size of components in the array. It does not develop its size at runtime. To resolve this issue, a collection framework is applied in Java which develops automatically.

How to Remove Duplicates From Array in Java

Duplicates From Array in Java

Remove Duplicates from Array Java by using Separate Index

This is the first approach to remove duplicates from array Java.

//write a program to remove duplicates from array in java

//Program to remove duplicates from array Java

public class RemoveDuplicateInArrayExample{  

     public static int removeDuplicateElements(int arr[], int n){  

         if (n==0 || n==1){  

             return n;  

         }    

         int j = 0;//for next element  

         for (int i=0; i < n-1; i++){  

             if (arr[i] != arr[i+1]){  

                 arr[j++] = arr[i];  

             }  

         }  

//remove duplicates from array java

         arr[j++] = arr[n-1];  

         return j;  

     }  

     public static void main (String[] args) 

{  

         int arr[] = {10,20,20,30,30,40,50,50};  

         int length = arr.length;  

         length = removeDuplicateElements(arr, length);  

         //printing array elements  

         for (int i=0; i<length; i++)  

            System.out.print(arr[i]+” “);  

     }  

Output for: How to remove duplicates from array in java by using separate index

10 20 30 40 50

Remove Duplicates From Array Java in Unsorted Array

If you have an unsorted array, you must first sort it. Use the Arrays.sort(arr) function to accomplish this. This is the second approach to remove duplicates from array Java.

//write a program to remove duplicates from array in java

//Program to remove duplicates from array Java

import java.util.Arrays;  

public class RemoveDuplicateInArrayExample{  

public static int removeDuplicateElements(int arr[], int n){  

         if (n==0 || n==1){  

             return n;  

         }  

         int[] temp = new int[n];  

         int j = 0;  

         for (int i=0; i<n-1; i++){  

             if (arr[i] != arr[i+1]){  

                 temp[j++] = arr[i];  

             }  

          }  

         temp[j++] = arr[n-1];  

         // Changing original array  

         for (int i=0; i<j; i++){  

             arr[i] = temp[i];  

         }  

         return j;  

     }  

//remove duplicates from array java

     public static void main (String[] args) {  

         int arr[] = {10,70,30,90,20,20,30,40,70,50};//unsorted array  

         Arrays.sort(arr);//sorting array  

         int length = arr.length;  

         length = removeDuplicateElements(arr, length);  

         //printing array elements  

         for (int i=0; i<length; i++)  

            System.out.print(arr[i]+” “);  

     }  

Output for: How to remove duplicates from array in java in Unsorted Array

10 20 30 40 50 70 90

Remove Duplicates From Array Java using Temporary Array

This is the third approach to remove duplicates from array Java.

//write a program to remove duplicates from array in java

//Program to remove duplicates from array Java

public class RemoveDuplicateInArrayExample{  

public static int removeDuplicateElements(int arr[], int n){  

         if (n==0 || n==1){  

             return n;  

         }  

         int[] temp = new int[n];  

         int j = 0;  

         for (int i=0; i<n-1; i++){  

             if (arr[i] != arr[i+1]){  

                 temp[j++] = arr[i];  

             }  

          }  

         temp[j++] = arr[n-1];  

         // Changing original array  

         for (int i=0; i<j; i++){  

             arr[i] = temp[i];  

         }  

         return j;  

     }  

//remove duplicates from array java

     public static void main (String[] args) {  

         int arr[] = {10,20,20,30,30,40,50,50};  

         int length = arr.length;  

         length = removeDuplicateElements(arr, length);  

         //printing array elements  

         for (int i=0; i<length; i++)  

            System.out.print(arr[i]+” “);  

     }  

Output for: How to remove duplicates from array in java using Temporary Array

10 20 30 40 50

Types of Array in Java

There are two types of arrays:

  • Single Dimensional Array
  • Multidimensional Array

Single Dimensional Array in Java

Single Dimensional Array in Java

Understanding Single Dimensional Array is very beneficial in addition to learning to remove duplicates from array Java.

Syntax to Declare an Array in Java

dataType[] arr; (or)  

dataType []arr; (or)  

dataType arr[];  

Instantiation of an Array in Java

arrayRefVar=new datatype[size]; 

Example of Java Array

Let us see the basic illustration of java array, in which we’re about to declare, instantiate, initialize and then traverse an array.

//Java Program for instance 

//how you can declare, instantiate, initialize 

//and then traverse the Java array.  

class Testarray{  

public static void main(String args[]){  

int a[]=new int[5];//declaration & instantiation  

a[0]=10;//initialization  

a[1]=20;  

a[2]=70;  

a[3]=40;  

a[4]=50;  

//traversing array  

for(int i=0;i<a.length;i++) //length is the property of array  

System.out.println(a[i]);  

}} 

Output:

10

20

70

40

50

Declaration, Instantiation and Initialization of Java Array

For learning the concept to remove duplicates from array Java, it is necessary that we are aware of declaration, instantiation and initialization.

We may declare, instantiate, and initialize the Java array as a group by doing the following:

int a[]={33,3,4,5}; //declaration, instantiation & initialization 

Let’s have a look at a simple example of how to print this array:

//Java Program to show the use of declaration, instantiation   

//and initialization of Java array in one line  

class Testarray1{  

public static void main(String args[]){  

int a[]={33,3,4,5};//declaration, instantiation & initialization  

//printing array  

for(int i=0;i<a.length;i++) //length is property of the array  

System.out.println(a[i]);  

}} 

Output:

33

3

4

5

For-each Loop for Java Array

We can additionally print the Java array making use of for-each loop. The Java for-each loop produces the array components one by one. It contains an array element in a variable, consequently executes the body of the loop.

The syntax of the for-each loop is provided below:

for(data_type variable:array){  

//body of the loop  

Let’s look at an example of employing the for-each loop to output the items of a Java array:

//Java Program to print the array components applying the for-each loop  

class Testarray1{  

public static void main(String args[]){  

int arr[]={33,3,4,5};  

//printing the array utilizing the for-each loop  

for(int i:arr)  

System.out.println(i);  

}} 

Output:

33

3

4

5

For-each loop is important for learning the concept to remove duplicates from array Java.

Java Array to Method

We can forward the Java array to method so that we can reuse exactly the same logic on virtually any array. Java Array to method is very beneficial in addition to learning to remove duplicates from array Java.

Let us see the user-friendly illustration to get the least number of an array making use of a method:

//A Java programme that illustrates how to pass an array.  

//to method.  

class Testarray2{  

//implementing a method that takes an array as a parameter 

static void min(int arr[]){  

int min=arr[0];  

for(int i=1;i<arr.length;i++)  

  if(min>arr[i])  

   min=arr[i]; 

System.out.println(min);  

}  

public static void main(String args[]){  

int a[]={33,3,4,5};//declaring and initializing an array  

min(a);//passing array to method  

}} 

Output:

3

Anonymous Array in Java

Java supports the characteristic of an anonymous array, therefore you do not have to declare the array while passing an array to the method. Anonymous array is very beneficial in addition to learning to remove duplicates from array Java.

//Java Program to show the example of passing an anonymous array  

//to method.  

public class TestAnonymousArray{  

//creation of a method that 

//receives an array as a parameter  

static void printArray(int arr[]){  

for(int i=0;i<arr.length;i++)  

System.out.println(arr[i]);  

public static void main(String args[]){  

printArray(new int[]{10,22,44,66}); 

//passing anonymous array to method  

}} 

Output:

10

22

44

66

R
eturning Array from the Method

We can additionally get back an array from the method in Java.

//Java Program to return an array from the method  

class TestReturnArray{  

//creating method that returns an array  

static int[] get(){  

return new int[]{10,30,50,90,60};  

}  

public static void main(String args[]){  

//calling method that returns an array  

int arr[]=get();  

//printing the values of an array  

for(int i=0;i<arr.length;i++)  

System.out.println(arr[i]);  

}} 

Output:

10

30

50

90

60

ArrayIndexOutOfBoundsException

When traversing an array, the Java Virtual Machine (JVM) throws an ArrayIndexOutOfBoundsException if the length of the array is negative, equal to the array size, or more than the array size. ArrayIndexOutOfBoundsException is very beneficial in addition to learning to remove duplicates from array Java.

//Java Program to illustrate the case of   

//ArrayIndexOutOfBoundsException in a Java Array.  

public class TestArrayException{  

public static void main(String args[]){  

int arr[]={50,60,70,80};  

for(int i=0;i<=arr.length;i++){  

System.out.println(arr[i]);  

}  

}} 

Output:

Exception in thread “main” java.lang.ArrayIndexOutOfBoundsException: 4

at TestArrayException.main(TestArrayException.java:5)

50

60

70

80

Multi-Dimensional Array in Java

Multi Dimensional Array in Java

Data is kept in a row and column based index in this situation (also known as matrix form). Being aware of multidimensional array in Java is very beneficial in addition to learning to remove duplicates from array Java.

Syntax to Declare Multidimensional Array in Java:

dataType[][] arrayRefVar; (or)  

dataType [][]arrayRefVar; (or)  

dataType arrayRefVar[][]; (or)  

dataType []arrayRefVar[];  

Example to instantiate Multidimensional Array in Java

int[][] arr=new int[3][3];

//3 row & 3 column 

Example to initialize Multidimensional Array in Java

arr[0][0]=1;  

arr[0][1]=2;  

arr[0][2]=3;  

arr[1][0]=4;  

arr[1][1]=5;  

arr[1][2]=6;  

arr[2][0]=7;  

arr[2][1]=8;  

arr[2][2]=9; 

Example of Multidimensional Java Array

Let’s look at a quick example of declaring, instantiating, initializing, and printing a two-dimensional array.

//Java Program to show 

//use of multidimensional array  

class Testarray3{  

public static void main(String args[]){  

//declaring & initializing 2D array  

int arr[][]={{1,2,3},{2,4,5},{4,4,5}};  

//printing 2D array  

for(int i=0;i<3;i++){  

  for(int j=0;j<3;j++){  

    System.out.print(arr[i][j]+” “);  

  }  

  System.out.println();  

}  

}} 

Output:

1 2 3

2 4 5

4 4 5

Jagged Array in Java

A jagged array is created when the number of columns in a 2D array is odd. To put it another way, it’s an array of arrays with varying numbers of columns. Being aware of jagged arrays is very beneficial in addition to learning to remove duplicates from array Java.

//Java Program to show the jagged array  

class TestJaggedArray{  

     public static void main(String[] args){  

         //declaring a 2D array with odd columns  

         int arr[][] = new int[3][];  

         arr[0] = new int[3];  

         arr[1] = new int[4];  

         arr[2] = new int[2];  

         //initializing a jagged array  

         int count = 0;  

         for (int i=0; i<arr.length; i++)  

             for(int j=0; j<arr[i].length; j++)  

                 arr[i][j] = count++;  

         //printing data of jagged array   

         for (int i=0; i<arr.length; i++){  

             for (int j=0; j<arr[i].length; j++){  

                 System.out.print(arr[i][j]+” “);  

             }  

             System.out.println();//new line  

         }  

     }  

Output:

0 1 2

3 4 5 6

7 8

Class Name of Java Array

An array is an object in Java. A proxy class is constructed for array objects, whose name may be acquired using the getClass().getName() function on the object. Understanding of class name is very beneficial in addition to learning to remove duplicates from array Java.

//Java Program for getting the class name of array in Java  

class Testarray4{  

public static void main(String args[]){  

//declaration & initialization of array  

int arr[]={4,4,5};  

//getting class name of the Java array  

Class c=arr.getClass();  

String name=c.getName();  

//printing class name of the Java array   

System.out.println(name);  

}} 

Output:

I

Copying a Java Array

The arraycopy() function of the System class can be used to copy an array to another. Awareness of the technique for copying a Java array is useful in addition to learning to remove duplicates from array Java.

Syntax of arraycopy method

public static void arraycopy(  

Object src, int srcPos,Object dest, int destPos, int length  

Example of Copying an Array

//Java Program for copying 

//a source array to 

//a destination array in Java  

class TestArrayCopyDemo {  

     public static void main(String[] args) {  

         //declaring a source array  

         char[] copyFrom = { ‘d’, ‘e’, ‘c’, ‘a’, ‘f’, ‘f’, ‘e’,  

                 ‘i’, ‘n’, ‘a’, ‘t’, ‘e’, ‘d’ };  

         //declaring a destination array  

         char[] copyTo = new char[7];  

         //copying array using System.arraycopy() method  

         System.arraycopy(copyFrom, 2, copyTo, 0, 7);  

         //printing the destination array  

         System.out.println(String.valueOf(copyTo));  

     }  

Output:

caffein

Cloning an Array in Java

Cloning an Array in Java

Since, Java array applies the Cloneable interface, we can develop the clone of the Java array. If we generate the clone of a single-dimensional array, it results in the deep copy belonging to the Java array. It means, it is going to copy the real value. Nevertheless, in case we develop the clone associated with a multidimensional array, it makes the shallow copy of the Java array and this implies it duplicates the references. Awareness of cloning is also very beneficial in addition to learning to remove duplicates from array Java.

//Java Program to clone the array  

class Testarray1{  

public static void main(String args[]){  

int arr[]={33,3,4,5};  

System.out.println(“Printing original array:”);  

for(int i:arr)  

System.out.println(i);  

System.out.println(“Printing clone of the array:”);  

int carr[]=arr.clone();  

for(int i:carr)  

Syste
m.out.println(i);  

System.out.println(“Are both equal?”);  

System.out.println(arr==carr);  

}} 

Output:

Printing original array:

33

3

4

5

Printing clone of the array:

33

3

4

5

Are both equal?

False

Addition of 2 Matrices in Java

Let’s look at a simple example of adding two matrices. Addition of two matrices is very advantageous in addition to learning to remove duplicates from array Java.

//Java Program to show 

//the addition of 2 matrices in Java

class Testarray5{  

public static void main(String args[]){  

//creating two matrices  

int a[][]={{1,3,4},{3,4,5}};  

int b[][]={{1,3,4},{3,4,5}};  

//creating another matrix to store the sum of 2 matrices  

int c[][]=new int[2][3];  

//adding & printing addition of 2 matrices  

for(int i=0;i<2;i++){  

for(int j=0;j<3;j++){  

c[i][j]=a[i][j]+b[i][j];  

System.out.print(c[i][j]+” “);  

}  

System.out.println();//new line  

}  

}} 

Output:

2 6 8

6 8 10

Multiplication of 2 Matrices in Java

In the instance of matrix multiplication, a one-row component of the primary matrix is multiplied by all of the columns of the 2nd matrix which could be known by the image provided below. Learning multiplication is favorable in addition to learning to remove duplicates from array Java. 

Reference Image

Let’s look at a simple example of multiplying two three-row and three-column matrices.

//Java Program to multiply two matrices  

public class MatrixMultiplicationExample{  

public static void main(String args[]){  

//creating two matrices    

int a[][]={{1,1,1},{2,2,2},{3,3,3}};    

int b[][]={{1,1,1},{2,2,2},{3,3,3}};    

//creating another matrix to stash the multiplication of two matrices    

int c[][]=new int[3][3];  //3 rows and 3 columns  

//multiplying & printing multiplication of 2 matrices    

for(int i=0;i<3;i++){    

for(int j=0;j<3;j++){    

c[i][j]=0;  

for(int k=0;k<3;k++)  

{  

c[i][j]+=a[i][k]*b[k][j];  

}//end of k loop  

System.out.print(c[i][j]+” “);  //printing matrix element  

}//end of j loop  

System.out.println();//new line    

}    

}} 

Output:

6 6 6

12 12 12

18 18 18

Program to Print the Duplicate Elements of an Array

You have already learnt to remove duplicates from array Java. Now let us see a program to print the duplicate elements of an array.

public class DuplicateElement {  

     public static void main(String[] args) {  

         //Initialize array   

         int [] arr = new int [] {1, 2, 3, 4, 2, 7, 8, 8, 3};   

         System.out.println(“Duplicate elements in given array: “);  

         //Searches for duplicate element  

         for(int i = 0; i < arr.length; i++) {  

             for(int j = i + 1; j < arr.length; j++) {  

                 if(arr[i] == arr[j])  

                     System.out.println(arr[j]);  

             }  

         }  

     }  

Output:

Duplicate elements in given array:

2

3

8

Conclusion to Remove Duplicates from Array Java

So coming to the end we looked at three different approaches to remove duplicates from array Java. These were Remove Duplicates From Array Java using separate index, Remove Duplicates From Array Java in Unsorted Array, Remove Duplicates From Array Java using Temporary Array.

Additionally we also defined Array, Java. We also learned about what are the types of array Java along with that many other related topics. We hope you were able to grasp the concept to remove duplicates from array Java. You can check out our other blogs: 25+ Supply Chain Management Interview Questions, Complete Guide on Data Mining Algorithms and more here.

Frequently Asked Question’s

1. How do I remove all Duplicates from a String?

The aim is to remove any duplicates in the given string S. The method for removing duplicates in a string is shown below:

import java.util.*;

class GFG

{

static String removeDuplicate(char str[], int n)

{

     // Used as index in the modified string

     int index = 0;

     // Traverse through all characters

//java remove duplicates from array of strings

     for (int i = 0; i < n; i++)

     {

         // Check if str[i]  

//present before it

         int j;

         for (j = 0; j < i; j++)

         {

             if (str[i] == str[j])

             {

                 break;

             }

         }

         // If not present 

//then add it to

         // result.

         if (j == i)

         {

             str[index++] = str[i];

         }

     }

     return String.valueOf(Arrays.copyOf(str, index));

}

// Driver code

//java remove duplicates from array of strings

public static void main(String[] args)

{

     char str[] = “datatrained”.toCharArray();

     int n = str.length;

     System.out.println(removeDuplicate(str, n));

}

}

Output: 

datrine

Let’s move on to the 2nd FAQ to remove duplicates from array Java blog.

2. How do you remove Duplicates from Unsorted Array?

Let’s see how to remove duplicates from unsorted array java. We can do so by applying the Map data structure.

// remove duplicates from unsorted array java

// Java program to remove

// the duplicates from the array.

import java.util.HashMap;

class GFG

{

static void removeDups(int[] arr, int n)

{

     // Hash map 

// will store the

     // elements which have 

// appeared previously.

     HashMap<Integer,

             Boolean> mp = new HashMap<>();

     for (int i = 0; i < n; ++i)

     {

         // Print the element 

//if it is not

         // there in the hash map

         if (mp.get(arr[i]) == null)

             System.out.print(arr[i] + ” “);

         // Insert the element 

// in hashmap

         mp.put(arr[i], true);

     }

}

// Driver Code

public static void main(String[] args)

{

     int[] arr = { 1, 2, 5, 1, 7, 2, 4, 2 };

     int n = arr.length;

     removeDups(arr, n);

}

}

Output:

1 2 5 7 4

Let’s move on to the 3rd FAQ to remove duplicates from array Java blog.

3. How do you remove Duplicates from a Set?

Set data structure to remove duplicates from an unsorted array.

// Java program to remove duplicates

// from unsorted array

import java.util.*;

class GFG {

// Function to remove duplicate from array

public static void removeDuplicates(int[] arr)

{

     LinkedHashSet<Integer> set

         = new LinkedHashSet<Integer>();

     // adding elements to LinkedHashSet

     for (int i = 0; i < arr.length; i++)

         set.add(arr[i]);

     // Print the elements of LinkedHashSet

     System.out.print(set);

}

// Driver code

public static void main(String[] args)

{

     int arr[] = { 1, 2, 5, 1, 7, 2, 4, 2 };

     // Function call

     removeDuplicates(arr);

}

}

Output:

[ 4 7 5 1 2 ]

Let’s move on to the 4th FAQ to remove duplicates from array Java blog.

4. How do you remove Duplicate elements from ArrayList in Java without using Collections?

Let us now find how to remove duplicates from array in java without using collections. The following is a Program to remove duplicates from ArrayList without using collections:

//how to remove duplicates from array in java without using collections

package arrayListRemoveduplicateElements;

import java.util.ArrayList;

public class RemoveDuplicates {

public static void main(String[] args){

     ArrayList<Object> al = new ArrayList<Object>();

     al.add(“java”);

     al.add(‘a’);

     al.add(‘b’);

     al.add(‘a’);

     al.add(“java”);

     al.add(10.3);

     al.add(‘c’);

     al.add(14);

     al.add(“java”);

     al.add(12);

System.out.println(“Before Remove Duplicate elements:”+al);

for(int i=0;i<al.size();i++){

  for(int j=i+1;j<al.size();j++){

             if(al.get(i).equals(al.get(j))){

                 al.remove(j);

                 j–;

             }

     }

  }

     System.out.println(“After Removing duplicate elements:”+al);

}

}

Output for: How to remove duplicates from array in java without using collections

Before Remove Duplicate elements:[java, a, b, a, java, 10.3, c, 14, java, 12]

After Removing duplicate elements:[java, a, b, 10.3, c, 14, 12]

 

Let’s move on to the 5th FAQ to remove duplicates from array Java blog.

5. How can we avoid Duplicate Records in JPA?

There are two options for dealing with this issue:

  • Declare the object you’re joining as a Set.
  • Make advantage of the Results Transformer for Distinct Root Entities.

Declare the object you’re joining as a Set:

Instead of using something like a List as the backing collection, you’ll need to use a Set. Here is an example:

import java.util.Set;

import javax.persistence.CascadeType;

import javax.persistence.Column;

import javax.persistence.Entity;

import javax.persistence.GeneratedValue;

import javax.persistence.GenerationType;

import javax.persistence.Id;

import javax.persistence.OneToMany;

import javax.persistence.Table;

@Entity

@Table(name=”users”)

public class User

{

  private Long userId;

  private String username;

  private String password;

  private Set<LoginHistory> loginHistory;

  @Id

  @GeneratedValue(strategy=GenerationType.AUTO)

  @Column(name=”user_id”)

  public Long getUserId()

    {

    return userId;

    }

    public void setUserId(Long userId)

    {

    this.userId = userId;

    }

    public String getUsername()

    {

    return username;

    }

    public void setUsername(String username)

    {

    this.username = username;

    }

    public String getPassword()

    {

    return password;

    }

    public void setPassword(String password)

    {

    this.password = password;

    }

    @OneToMany(cascade=CascadeType.ALL, mappedBy=”user”)

    public Set<LoginHistory> getLoginHistory()

    {

    return loginHistory;

    }

    public void setLoginHistory(Set<LoginHistory> loginHistory)

    {

    this.loginHistory = loginHistory;

    }

}

The trick is to deploy a Set as a collection of child things once again. As a result, we used Set<LoginHistory> in our previous example. Let’s move on to the 6th FAQ to remove duplicates from array Java blogs.

6. How can we prevent double submission of Form UI in Spring?

You can find several ways to avoid double submits, and that could be combined:

  1. Use JavaScript to turn off the key a couple of ms upon click. It will avoid various submits being brought on by impatient people clicking several times on the key.
  2. Transmit reroute after submit, this is referred to as Post-Redirect-Get (PRG) pattern. This tends to avoid various submits being triggered by users pressing F5 on the result page and neglecting the web browser warning that the details will be resend, or even navigating back and forth by internet browser back/forward buttons and disregarding a similar warning.

Create a unique token if the page is requested and set in both the session scope and as a hidden field of the form. In the course of processing, determine if the token is there and then remove it right away from the session and keep on processing. If the token isn’t there, then block processing. It will avoid the above mentioned sorts of issues. 

In Spring you can employ RedirectView as implementation on the PRG pattern (as outlined in point two). The additional 2 points have to be implemented yourself. Let’s move on to the 7th FAQ to remove duplicates from array Java blog.

7. How do you avoid Duplicate names in Java?

In this solution we will be considering the right way to avoid the addition of duplicates into our ArrayList. If an ArrayList has 3 duplicate elements, but at the end, just the ones which are distinctive are considered into the ArrayList and the repetitions are ignored could be achieved with the use of several techniques mentioned below.

Example:

Input : [1, 1, 2, 2, 3, 3, 4, 5, 8]

Output: [1, 2, 3, 4, 5, 8]

Input : [1, 1, 1, 1, 1, 1, 1, 1, 1]

Output: [1]

Approach: contains() method

  1. Add components one by one.
  2. Look for their existence with the help of the contains method.
  3. Ignore the present aspect in case it returns true.
  4. Else include the element.

import java.util.ArrayList;

class GFG {

public static void main(String[] args)

{

     // Input

     int array[] = { 1, 1, 2, 2, 3, 3, 4, 5, 8 };

     // Creating an empty ArrayList

     ArrayList<Integer> ans = new ArrayList<>();

     for (int i : array) {

         // Checking if the element is already present or

         // not

         if (!ans.contains(i)) {

             // Adding the element to the ArrayList if it

             // is not present

             ans.add(i);

         }

     }

     // Printing the elements of the ArrayList

     for (int i : ans) {

         System.out.print(i + ” “);

     }

}

}

Output:

1 2 3 4 5 8

Time Complexity: O( N2)

Space Complexity: O(1)

Let’s move on to the 8th FAQ to remove duplicates from array Java blog.

Tagged in :

One response to “How to Remove Duplicates from Array Java | DataTrained”

  1. […] Also Read : How to Remove Duplicates from Array in Java […]

UNLOCK THE PATH TO SUCCESS

We will help you achieve your goal. Just fill in your details, and we'll reach out to provide guidance and support.