Wednesday, 26 April 2017

Java Program to Remove Duplicate Elements From Int Array ?

Write a java program to remove duplicate elements from the given array. Your program or method should take an array of integers as input and should return another array which should contain only unique elements from the input array. For example, if {1,2,3,5,5,1,2,3} is the input array then your program or method should return {1,2,3,5} as output.

 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
42
43
44
45
46
public class RemoveDuplicateElementFromArray {

 public static void remove(int[] arr){
  int arrayLength = arr.length;
  
  System.out.println("Array With Duplicate Elements : ");
  //This Loop is Used to Print Complete Array
  for(int i : arr)
  {
   System.out.print(i+",");
  }
  
  for(int i=0; i<arrayLength; i++)
  {
   for(int j=i+1; j<arrayLength; j++)
   {
    if(arr[i] == arr[j])
    {
     arr[j] = arr[arrayLength - 1];
     arrayLength--;
     j--;
    }
   }
  }
  
  //Below Loop Prints the Unique Elements From array
  System.out.println("\nArray With Unique Elements : ");
  for(int i = 0; i<arrayLength; i++)
  {
   System.out.print(arr[i]+",");
  }
  System.out.println("\n\n");
 }
 public static void main(String[] args) {
  
  remove(new int[] {4, 3, 2, 4, 9, 2});
        
  remove(new int[] {1, 2, 1, 2, 1, 2});
         
  remove(new int[] {15, 21, 11, 21, 51, 21, 11});
         
  remove(new int[] {7, 3, 21, 7, 34, 18, 3, 21});
        
 }

}

Output :



      
Blog Author - Pushkar Khosla,
Software Developer by Profession with 3.0 Yrs of Experience , through this blog i'am sharing my industrial Java Knowledge to entire world. For any question or query any one can comment below or mail me at pushkar.itsitm52@gmail.com.

This blog is all about to learn Core Java ,Interview Programs and Coding tricks to polish your Java Knowledge. If you like the content of this blog please share this with your friends.



No comments:

Post a Comment