In this tutorial you will learn about the Java Program to Remove Duplicate Element in an array and its application with practical example.
In this tutorial, we will learn to create a Java Program to Remove Duplicate Element in an array using java programming.
Prerequisites
Before starting with this tutorial, we assume that you are best aware of the following Java programming concepts:
- Java Operators.
- Basic Input and Output function in Java.
- Class and Object in Java.
- Basic Java programming.
- If-else statements in Java.
- For loop in Java.
Java Program to Remove Duplicate Element in an array
In this program we will find duplicate element in an array if-else statement and loop. We would first declared and initialized the required variables. Next, we will find repeated number in an array.lets have a look at the code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
// Java Program to Remove Duplicate Elements public class Duplicate { public static int remove(int arr[], int size) { if (size == 0 || size == 1) { return size; } // creating another array and removing duplicate elements int[] temp = new int[size]; int j = 0; for (int i = 0; i < size - 1; i++) { if (arr[i] != arr[i + 1]) { temp[j++] = arr[i]; } } temp[j++] = arr[size - 1]; for (int i = 0; i < j; i++) { arr[i] = temp[i]; } return j; } public static void main(String[] args) { int arr[] = { 1, 1, 2, 2, 3, 4}; int number = arr.length; number = remove(arr, number); // Printing The array elements System.out.println("printing removed duplicate array elements "); for (int i = 0; i < number; i++) System.out.print(arr[i] + " "); } } |
Output
In the above program, we have first declared and initialized a set variables required in the program.
- arr= it will hold array values
- number and size= it will hold length of an array.
- i and j for iteration
- temp = it will hold temporary value of an array.
After declaring variables we initiate values in an array[].
and with the help length we find the length of an array.
Now we will pass arr[] and length to remove() method where we remove duplicate values within the array[].
Steps to remove duplicate elements
- Create a temp array temp[] to store unique values of elements.
- travel through array and copy all the unique elements of arr[] to temp[]. and count unique elements.
- Copy j elements from temp[] to arr[].
and finally print sorted array.