Wednesday, January 14, 2015

Remove duplicate elements from an array in Java


In many programming problems we need to remove duplicate elements from an array.In this tutorial lets see how to remove duplicates from an array in java.

  public static int[] remove_duplicates(int[] a){
  int comp,n,numOfRepeats=0;

  for(int i=0;i<a.length;i++){
   n=0;
   comp=a[i];
   for(int j=0;j<a.length;j++){
    if(comp==a[j]&&(i!=j)){
     numOfRepeats++; 
    }
   }
  }

  int sol[]=new int[(a.length-numOfRepeats)];

  int solIndex=0;

  for(int i=0;i<a.length;i++){
   n=0;
   comp=a[i];
   for(int j=0;j<a.length;j++){
    if(comp==a[j]&&(j!=i)){
     n=2;
     break;
    }
   }
   if(n==0){
    sol[solIndex]=comp;
    solIndex++;
   }
  }
  return sol;
 }


The above code is a simple code that any one can imagine. But it may not be very efficient in some cases.
   In java there are lot of built in classes to make this kind of things easy. By using java collection we can create a method as follows.


  public static Integer[] removeDuplicates(Integer[] arr) {

  return new HashSet<Integer>(Arrays.asList(arr)).toArray(new Integer[0]);

}


you can explore more about duplicate removing algorithms using this link..

No comments:

Post a Comment

Optimize you working enviorenment : Single command to create & move to a directory in linux (C Shell, Bash)

Usually move to a directory just after creating is bit of a anxious task specially if the directory name is too long. mkdir long-name-of...