Sunday, 5 January 2014

how-to-remove-duplicates-from-array-java-without-collection-API


In this program, we have not used any collection class to remove duplicates, In this example, we are removing duplicates elements from array and copying them into newly result array.


1:  import java.util.Arrays;  
2:  /**  
3:   * @author Ajaykumar.gupta  
4:   *  
5:   */  
6:  public class RemoveDublicateElements {  
7:      /**  
8:       * Suppose let have a arrays of integer elements.  
9:       */  
10:      private static int[] array = { 1, 2, 3, 4, 2, 4, 5, 6, 7, 1, 3, 5, 9, 8, 7,  
11:              6, 7, 8, 9, 0, 8, 6, 5, 0, 5, 4, 3, 2, 5, 6, 0, 1, 2, 3, 4, 5, 6 };  
12:      public static void main(String args[]){  
13:          int[] values = removeDublicate(array);  
14:          for(int i=0; i < values.length ;i++ ){  
15:              System.out.print(values[i]+" ");  
16:          }  
17:      }  
18:      private static int[] removeDublicate(int[] array){  
19:          /**  
20:           * Sort Array elements first.  
21:           */  
22:          Arrays.sort(array);  
23:          // Allocated a new array with same size.  
24:          int []result= new int[array.length];  
25:          // Assigned a first element into a previous variable.  
26:          int previous = result[0];  
27:          // Assigned a smallest elements into Array zero position.  
28:          result[0] = previous;  
29:          int num = 1;  
30:          for(int i=1; i <array.length;i++){  
31:              int ch = array[i];  
32:              // Logic is applied for removed duplicate elements and assigned to result array  
33:              if(previous != ch){  
34:                  result[num++] = ch;  
35:              }  
36:              previous = ch;  
37:          }  
38:          // Removed Blank space(Zero) and copy exect size of array and return it to caller.  
39:          return Arrays.copyOf(result, num);  
40:      }  
41:  }  

Output : 0 1 2 3 4 5 6 7 8 9

No comments:

Post a Comment